// 管理后台JavaScript代码

// API基础配置
const API_BASE = '../api/';

// 全局变量
let currentVerificationData = null;
let currentAdmin = null;
let userPermissions = [];
let reservationNoticeQuill = null;
let enterNoticeQuill = null;
let activityNoticeQuill = null;
let reservationNoticeEditor = null;
let enterNoticeEditor = null;

// 退出登录（放在顶部确保立即可用）
function logout() {
    console.log('logout function called'); // 调试信息
    if (confirm('确定要退出登录吗？')) {
        localStorage.removeItem('admin_token');
        localStorage.removeItem('admin_info');
        sessionStorage.removeItem('admin_token');
        sessionStorage.removeItem('admin_info');
        window.location.href = 'login.html';
    }
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    checkLoginStatus();
    
    // 显示当前日期
    document.getElementById('currentDate').textContent = new Date().toLocaleDateString('zh-CN');
    
    // 设置默认查询日期为今天
    document.getElementById('reservationDate').value = new Date().toISOString().split('T')[0];
    
    // 设置回车键触发验证
    document.getElementById('verificationCode').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            verifyReservation();
        }
    });
    
    // 轮播图搜索框回车事件
    document.addEventListener('DOMContentLoaded', function() {
        const carouselSearchInput = document.getElementById('carouselSearch');
        if (carouselSearchInput) {
            carouselSearchInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    searchCarousels();
                }
            });
        }
    });
    
    // 调试：确保logout函数已定义
    console.log('logout function defined:', typeof logout);
});

// 页面切换
function showPage(pageName) {
    // 检查权限
    const pageElement = document.querySelector(`[onclick="showPage('${pageName}')"]`);
    const requiredPermission = pageElement?.getAttribute('data-permission');
    if (requiredPermission && !hasPermission(requiredPermission)) {
        showAlert('', '权限不足，无法访问此页面');
        return;
    }
    
    // 隐藏所有页面内容
    const tabContents = document.querySelectorAll('.tab-content');
    tabContents.forEach(content => content.classList.remove('active'));
    
    // 移除所有菜单项的激活状态
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => item.classList.remove('active'));
    
    // 显示选中的页面内容
    document.getElementById(pageName).classList.add('active');
    
    // 激活对应的菜单项
    if (pageElement) {
        pageElement.classList.add('active');
    }
    
    // 更新页面标题
    const pageTitles = {
        'dashboard': 'HOME',
        'config': '系统配置', 
        'timeslots': '时段管理',
        'closures': '闭馆设置',
        'reservations': '个人预约管理',
        'team-reservations': '团队预约管理',
        'users': '用户管理',
        'activities': '活动管理',
        'feedback': '用户反馈',
        'volunteers': '志愿者管理',
        'verification': '核验中心',
        'verification-logs': '核销记录管理',
        'carousels': '轮播图管理',
        'chapters': '篇章管理',
        'exhibits': '展项管理',
        'items': '展品管理',
        'media': '多媒体管理',
        'subscribe-templates': '订阅消息模板',
        'admin': '管理员管理',
        'roles': '角色管理',
        'logs': '系统日志',
        'common-visitors': '常用观众管理'
    };
    
    const pageTitle = document.getElementById('pageTitle');
    if (pageTitle) {
        pageTitle.textContent = pageTitles[pageName] || pageName;
    }
    
    // 根据页面加载对应数据
    switch(pageName) {
        case 'dashboard':
            loadDashboard();
            break;
        case 'users':
            loadUsers();
            break;
        case 'activities':
            loadActivities();
            break;
        case 'reservations':
            // 个人预约页面自动加载全部数据
            loadReservations();
            break;
        case 'team-reservations':
            loadTeamReservations();
            break;
        case 'carousels':
            loadCarousels();
            break;
        case 'chapters':
            loadChapters();
            break;
        case 'exhibits':
            loadExhibits();
            loadChapterFilterOptions();
            break;
        case 'items':
            loadItems();
            loadItemFilterOptions();
            break;
        case 'media':
            loadMedia();
            break;
        case 'subscribe-templates':
            loadSubscribeTemplates();
            loadTemplateFilterOptions();
            break;
        case 'admin':
            loadAdmins();
            break;
        case 'roles':
            loadRoles();
            break;
        case 'logs':
            loadLogs();
            break;
        case 'common-visitors':
            loadVisitorList();
            break;
        case 'volunteers':
            loadVolunteers();
            break;
        case 'feedback':
            loadFeedbacks();
            break;
    }
}

// API请求封装
async function apiRequest(endpoint, options = {}) {
    try {
        const token = getToken();
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': token ? `Bearer ${token}` : ''
            }
        };
        
        const response = await fetch(API_BASE + endpoint, {
            ...defaultOptions,
            ...options
        });
        
        if (response.status === 401) {
            // 未授权，跳转到登录页
            window.location.href = 'login.html';
            return;
        }
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('API请求失败:', error);
        throw error;
    }
}

// 获取Token
function getToken() {
    return localStorage.getItem('admin_token') || sessionStorage.getItem('admin_token');
}

// 检查登录状态
async function checkLoginStatus() {
    const token = getToken();
    if (!token) {
        window.location.href = 'login.html';
        return;
    }
    
    try {
        const response = await apiRequest('admin_auth.php?action=profile');
        if (response.code === 200) {
            currentAdmin = response.data;
            userPermissions = currentAdmin.permissions || [];
            updateAdminInfo();
            initializePermissions();
            initializeData();
        } else {
            window.location.href = 'login.html';
        }
    } catch (error) {
        console.error('验证登录状态失败:', error);
        window.location.href = 'login.html';
    }
}

// 更新管理员信息显示
function updateAdminInfo() {
    if (currentAdmin) {
        document.getElementById('adminInfo').textContent = 
            `${currentAdmin.real_name || currentAdmin.username} (${currentAdmin.role_display_name})`;
    }
}

// 初始化权限控制
function initializePermissions() {
    // 检查每个需要权限的元素
    const permissionElements = document.querySelectorAll('[data-permission]');
    permissionElements.forEach(element => {
        const requiredPermission = element.getAttribute('data-permission');
        if (!hasPermission(requiredPermission)) {
            element.style.display = 'none';
        } else {
            element.style.display = '';
        }
    });
}

// 检查权限
function hasPermission(permission) {
    return userPermissions.includes(permission);
}

// 初始化数据加载
function initializeData() {
    // 初始化富文本编辑器
    initializeRichTextEditors();
    
    // 初始化加载数据
    loadDashboard();
    loadConfig();
    loadTimeSlots();
    loadClosures();
    loadRecentCheckins();
    
    // 如果有管理员权限，加载管理员数据
    if (hasPermission('admin.view')) {
        loadAdmins();
    }
    if (hasPermission('roles.view')) {
        loadRoles();
        loadPermissions();
    }
    
    // 加载用户管理数据
    if (hasPermission('users.view')) {
        loadUsers();
    }
    
    // 加载活动管理数据
    if (hasPermission('activities.view')) {
        loadActivities();
    }
}


// 初始化富文本编辑器
function initializeRichTextEditors() {
    const E = window.wangEditor;
    // 创建两个独立的编辑器实例
    reservationNoticeEditor = E.createEditor({
        selector: '#reservationNoticeEditor',
    });
    enterNoticeEditor = E.createEditor({
        selector: '#enterNoticeEditor',
    });
    const toolbarConfig = {}
    //排除指定的菜单,排除图片上传和视频上传
    toolbarConfig.excludeKeys = ['group-image','group-video']
    
    // 分别为每个编辑器创建工具栏
    const reservationNoticeToolbar = E.createToolbar({
        editor: reservationNoticeEditor,
        selector: '#reservationNoticeToolbar',
        config: toolbarConfig,
    });
    const enterNoticeToolbar = E.createToolbar({
        editor: enterNoticeEditor,
        selector: '#enterNoticeToolbar',
        config: toolbarConfig,
    });
    
}

// 显示警告信息
function showAlert(containerId, message, type = 'error') {
    const container = document.getElementById(containerId);
    container.innerHTML = `
        <div class="alert alert-${type === 'success' ? 'success' : 'error'}">
            ${message}
        </div>
    `;
    
    // 3秒后自动清除
    setTimeout(() => {
        container.innerHTML = '';
    }, 3000);
}

// 加载仪表板数据
async function loadDashboard() {
    try {
        const today = new Date().toISOString().split('T')[0];
        
        // 获取今日统计
        const statsResponse = await apiRequest(`verification.php?action=daily_statistics&date=${today}`);
        
        if (statsResponse.code === 200) {
            const { slot_stats, total_stats } = statsResponse.data;
            
            // 更新统计卡片
            document.getElementById('todayReserved').textContent = total_stats.total_reserved || 0;
            document.getElementById('todayCheckedIn').textContent = total_stats.total_checked_in || 0;
            
            
            // 更新时段统计表格
            updateSlotStatsTable(slot_stats);
        }
    } catch (error) {
        console.error('加载仪表板失败:', error);
        document.getElementById('todayReserved').textContent = '错误';
        document.getElementById('todayCheckedIn').textContent = '错误';
    }
}

// 更新时段统计表格
function updateSlotStatsTable(stats) {
    const tbody = document.getElementById('slotStatsTable');
    
    if (!stats || stats.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="loading">今日无开放时段</td></tr>';
        return;
    }
    
    tbody.innerHTML = stats.map(slot => `
        <tr>
            <td>${slot.slot_name || '未知'}</td>
            <td>${slot.start_time || ''} - ${slot.end_time || ''}</td>
            <td>${slot.reserved_count || 0}</td>
            <td>${slot.checked_in_count || 0}</td>
            <td>${slot.max_visitors || 0}</td>
            <td>${slot.available_count || 0}</td>
        </tr>
    `).join('');
}

// 加载系统配置
async function loadConfig() {
    try {
        const response = await apiRequest('admin/system_config.php?action=get_config');
        
        if (response.code === 200) {
            const configs = response.data;
            
            // 填充表单 - 处理配置项
            const advanceBookingDaysElement = document.getElementById('advanceBookingDays');
            const maxCompanionsElement = document.getElementById('maxCompanions');
            // 获取页面dom元素
            const VenueNameElement = document.getElementById('VenueName');
            const OpenTimeElement = document.getElementById('OpenTime');
            const AddressElement = document.getElementById('Address');
            const PhoneElement = document.getElementById('configPhone');
            const EmailElement = document.getElementById('Email');
            const SubwayElement = document.getElementById('Subway');
            const BusElement = document.getElementById('Bus');
            
            // 检查元素是否存在
            if (!advanceBookingDaysElement || !maxCompanionsElement) {
                showAlert('configAlert', '页面元素未找到，请刷新页面重试');
                return;
            }
            
            // 填充基础配置
            if (configs.advance_booking_days) {
                advanceBookingDaysElement.value = configs.advance_booking_days;
            }
            if (configs.max_companions) {
                maxCompanionsElement.value = configs.max_companions;
            }
            if (configs.venue_name) {
                VenueNameElement.value = configs.venue_name;
            }
            if (configs.open_time) {
                OpenTimeElement.value = configs.open_time;
            }
            if (configs.address) {
                AddressElement.value = configs.address;
            }
            if (configs.phone) {
                PhoneElement.value = configs.phone;
            }
            if (configs.email) {
                EmailElement.value = configs.email; 
            }
            if (configs.subway) {
                SubwayElement.value = configs.subway;
            }
            if (configs.bus) {
                BusElement.value = configs.bus;
            }
            // 填充富文本编辑器内容
            reservationNoticeEditor.setHtml(configs.reservation_notice);
            enterNoticeEditor.setHtml(configs.enter_notice);
        }
    } catch (error) {
        console.error('加载配置失败:', error);
        showAlert('configAlert', '加载配置失败：' + error.message);
    }
}

// 保存系统配置
async function saveConfig() {
    try {
        // 检查页面元素
        const advanceBookingDaysElement = document.getElementById('advanceBookingDays');
        const maxCompanionsElement = document.getElementById('maxCompanions');
        const VenueNameElement = document.getElementById('VenueName');
        const OpenTimeElement = document.getElementById('OpenTime');
        const AddressElement = document.getElementById('Address');
        const PhoneElement = document.getElementById('configPhone');
        const EmailElement = document.getElementById('Email');
        const SubwayElement = document.getElementById('Subway');
        const BusElement = document.getElementById('Bus');
        let configs = {}
        configs.advance_booking_days = advanceBookingDaysElement.value;
        configs.max_companions = maxCompanionsElement.value;
        configs.venue_name = VenueNameElement.value;
        configs.open_time = OpenTimeElement.value;
        configs.address = AddressElement.value;
        configs.phone = PhoneElement.value;
        configs.email = EmailElement.value;
        configs.subway = SubwayElement.value;
        configs.bus = BusElement.value;

        //把编辑器的内容赋值给表单字段
        console.log(reservationNoticeEditor);
        console.log(enterNoticeEditor);
        configs.reservation_notice = reservationNoticeEditor.getHtml();
        configs.enter_notice = enterNoticeEditor.getHtml();
        
        const response = await apiRequest('admin/system_config.php?action=update_config', {
            method: 'POST',
            body: JSON.stringify(configs)
        });

        if (response.code !== 200) {
            throw new Error(`保存 ${config.config_key} 失败: ${response.message}`);
        }
        
        showAlert('configAlert', '所有配置保存成功！', 'success');
    } catch (error) {
        console.error('保存配置失败:', error);
        showAlert('configAlert', '保存配置失败：' + error.message);
    }
}

// 加载时段管理
async function loadTimeSlots() {
    try {
        const response = await apiRequest('museum_config.php?action=get_time_slots');
        
        if (response.code === 200) {
            const slots = response.data;
            
            const tbody = document.getElementById('timeslotsTable');
            tbody.innerHTML = slots.map(slot => `
                <tr>
                    <td>${slot.slot_name}</td>
                    <td>${slot.start_time}</td>
                    <td>${slot.end_time}</td>
                    <td>${slot.max_visitors}</td>
                    <td>
                        <span class="status-badge ${slot.is_active == 1 ? 'status-open' : 'status-closed'}">
                            ${slot.is_active == 1 ? '启用' : '禁用'}
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-primary" onclick="editTimeSlot(${slot.id})">编辑</button>
                        <button class="btn btn-danger" onclick="deleteTimeSlot(${slot.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        }
    } catch (error) {
        console.error('加载时段管理失败:', error);
        document.getElementById('timeslotsTable').innerHTML = 
            '<tr><td colspan="6" class="loading">加载失败</td></tr>';
    }
}

// 加载闭馆日期
async function loadClosures() {
    try {
        const response = await apiRequest('museum_config.php?action=get_closure_dates');
        
        if (response.code === 200) {
            const closures = response.data;
            
            const tbody = document.getElementById('closuresTable');
            tbody.innerHTML = closures.map(closure => {
                // 处理闭馆类型显示
                let typeText = '';
                switch(closure.closure_type) {
                    case 'once': typeText = '单次闭馆'; break;
                    case 'range': typeText = '日期范围'; break;
                    case 'weekly': typeText = '每周重复'; break;
                    case 'monthly': typeText = '每月重复'; break;
                    case 'yearly': typeText = '每年重复'; break;
                    default: typeText = closure.closure_type;
                }
                
                return `
                <tr>
                    <td>${closure.closure_date || '规则闭馆'}</td>
                    <td>${typeText}</td>
                    <td>${closure.reason || '-'}</td>
                    <td>
                        <span class="status-badge ${closure.is_active == 1 ? 'status-open' : 'status-closed'}">
                            ${closure.is_active == 1 ? '生效' : '禁用'}
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-primary" onclick="editClosure(${closure.id})" style="margin-right: 0.5rem;">编辑</button>
                        <button class="btn btn-danger" onclick="deleteClosure(${closure.id})">删除</button>
                    </td>
                </tr>
                `;
            }).join('');
        }
    } catch (error) {
        console.error('加载闭馆日期失败:', error);
        document.getElementById('closuresTable').innerHTML = 
            '<tr><td colspan="5" class="loading">加载失败</td></tr>';
    }
}

// 加载预约列表
// 预约分页相关变量
let currentReservationPage = 1;
let reservationPageSize = 20;
let totalReservationPages = 0;
let totalReservationCount = 0;

// 加载预约列表 - 默认加载全部预约
async function loadReservations(page = 1) {
    try {
        currentReservationPage = page;
        document.getElementById('reservationsTable').innerHTML = 
            '<tr><td colspan="8" class="loading">加载中...</td></tr>';
        
        const response = await apiRequest(`admin_reservations.php?action=list&type=personal&page=${page}&limit=${reservationPageSize}`);
        
        if (response.code === 200) {
            displayReservations(response.data.reservations || response.data);
            updateReservationPagination(response.data.pagination || {
                current_page: 1,
                total_pages: 1,
                total_count: (response.data.reservations || response.data).length
            });
        } else {
            document.getElementById('reservationsTable').innerHTML = 
                '<tr><td colspan="8" class="loading">加载失败</td></tr>';
            showAlert('reservationsAlert', response.message || '加载预约列表失败');
        }
    } catch (error) {
        console.error('加载预约列表失败:', error);
        document.getElementById('reservationsTable').innerHTML = 
            '<tr><td colspan="8" class="loading">加载失败</td></tr>';
        showAlert('reservationsAlert', '加载预约列表失败：' + error.message);
    }
}

// 搜索预约
async function searchReservations(page = 1) {
    const name = document.getElementById('searchName').value.trim();
    const idCard = document.getElementById('searchIdCard').value.trim();
    const phone = document.getElementById('searchPhone').value.trim();
    const status = document.getElementById('searchStatus').value;
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    
    try {
        currentReservationPage = page;
        document.getElementById('reservationsTable').innerHTML = 
            '<tr><td colspan="8" class="loading">搜索中...</td></tr>';
        
        let url = `admin_reservations.php?action=search&type=personal&page=${page}&limit=${reservationPageSize}`;
        
        if (name) url += `&name=${encodeURIComponent(name)}`;
        if (idCard) url += `&id_card=${encodeURIComponent(idCard)}`;
        if (phone) url += `&phone=${encodeURIComponent(phone)}`;
        if (status) url += `&status=${status}`;
        if (startDate) url += `&start_date=${startDate}`;
        if (endDate) url += `&end_date=${endDate}`;
        
        const response = await apiRequest(url);
        
        if (response.code === 200) {
            displayReservations(response.data.reservations || response.data);
            updateReservationPagination(response.data.pagination || {
                current_page: 1,
                total_pages: 1,
                total_count: (response.data.reservations || response.data).length
            });
        } else {
            document.getElementById('reservationsTable').innerHTML = 
                '<tr><td colspan="8" class="loading">搜索失败</td></tr>';
            showAlert('reservationsAlert', response.message || '搜索失败');
        }
    } catch (error) {
        console.error('搜索预约失败:', error);
        document.getElementById('reservationsTable').innerHTML = 
            '<tr><td colspan="8" class="loading">搜索失败</td></tr>';
        showAlert('reservationsAlert', '搜索失败：' + error.message);
    }
}

// 重置搜索条件
function resetSearch() {
    document.getElementById('searchName').value = '';
    document.getElementById('searchIdCard').value = '';
    document.getElementById('searchPhone').value = '';
    document.getElementById('searchStatus').value = '';
    document.getElementById('startDate').value = '';
    document.getElementById('endDate').value = '';
    loadReservations(1);
}

// 显示预约列表
function displayReservations(reservations) {
    const tbody = document.getElementById('reservationsTable');
    
    if (!reservations || reservations.length === 0) {
        tbody.innerHTML = '<tr><td colspan="8" class="loading">暂无预约记录</td></tr>';
        return;
    }
    
    tbody.innerHTML = reservations.map(reservation => {
        // 处理状态显示
        let statusBadge = '';
        switch(reservation.status) {
            case 'confirmed':
                statusBadge = '<span class="status-badge status-open">已确认</span>';
                break;
            case 'pending':
                statusBadge = '<span class="status-badge status-warning">待确认</span>';
                break;
            case 'cancelled':
                statusBadge = '<span class="status-badge status-closed">已取消</span>';
                break;
            case 'completed':
                statusBadge = '<span class="status-badge status-completed">已完成</span>';
                break;
            default:
                statusBadge = `<span class="status-badge">${reservation.status}</span>`;
        }
        
        // 处理时段显示
        const timeSlot = reservation.slot_name ? 
            `${reservation.slot_name}<br><small>(${reservation.start_time}-${reservation.end_time})</small>` : 
            `${reservation.start_time || ''}-${reservation.end_time || ''}`;
        
        // 处理签到时间
        const checkInTime = reservation.check_in_time || '-';
        
        return `
            <tr>
                <td>${reservation.id}</td>
                <td>${reservation.visitor_name || '-'}</td>
                <td>${reservation.visit_date || '-'}</td>
                <td>${timeSlot}</td>
                <td>${statusBadge}</td>
                <td>${reservation.reservation_code || '-'}</td>
                <td>${checkInTime}</td>
                <td>${reservation.visitor_phone || '-'}</td>
            </tr>
        `;
    }).join('');
}

// 更新分页控件
function updateReservationPagination(pagination) {
    const paginationDiv = document.getElementById('reservationPagination');
    
    if (!pagination || pagination.total_pages <= 1) {
        paginationDiv.innerHTML = '';
        return;
    }
    
    totalReservationPages = pagination.total_pages;
    totalReservationCount = pagination.total_count;
    currentReservationPage = pagination.current_page;
    
    let paginationHtml = `
        <div style="display: flex; align-items: center; justify-content: center; gap: 10px;">
            <span style="color: #666; font-size: 14px;">
                共 ${totalReservationCount} 条记录，第 ${currentReservationPage}/${totalReservationPages} 页
            </span>
            <div style="display: flex; gap: 5px;">
    `;
    
    // 上一页
    if (currentReservationPage > 1) {
        paginationHtml += `
            <button class="btn btn-sm btn-secondary" onclick="goToReservationPage(${currentReservationPage - 1})">
                上一页
            </button>
        `;
    }
    
    // 页码按钮
    let startPage = Math.max(1, currentReservationPage - 2);
    let endPage = Math.min(totalReservationPages, currentReservationPage + 2);
    
    if (startPage > 1) {
        paginationHtml += `<button class="btn btn-sm btn-secondary" onclick="goToReservationPage(1)">1</button>`;
        if (startPage > 2) {
            paginationHtml += `<span style="padding: 0 5px;">...</span>`;
        }
    }
    
    for (let i = startPage; i <= endPage; i++) {
        const activeClass = i === currentReservationPage ? 'btn-primary' : 'btn-secondary';
        paginationHtml += `
            <button class="btn btn-sm ${activeClass}" onclick="goToReservationPage(${i})">${i}</button>
        `;
    }
    
    if (endPage < totalReservationPages) {
        if (endPage < totalReservationPages - 1) {
            paginationHtml += `<span style="padding: 0 5px;">...</span>`;
        }
        paginationHtml += `
            <button class="btn btn-sm btn-secondary" onclick="goToReservationPage(${totalReservationPages})">
                ${totalReservationPages}
            </button>
        `;
    }
    
    // 下一页
    if (currentReservationPage < totalReservationPages) {
        paginationHtml += `
            <button class="btn btn-sm btn-secondary" onclick="goToReservationPage(${currentReservationPage + 1})">
                下一页
            </button>
        `;
    }
    
    paginationHtml += `
            </div>
        </div>
    `;
    
    paginationDiv.innerHTML = paginationHtml;
}

// 跳转到指定页面
function goToReservationPage(page) {
    // 检查是否有搜索条件
    const hasSearchConditions = 
        document.getElementById('searchName').value.trim() ||
        document.getElementById('searchIdCard').value.trim() ||
        document.getElementById('searchPhone').value.trim() ||
        document.getElementById('searchStatus').value ||
        document.getElementById('startDate').value ||
        document.getElementById('endDate').value;
    
    if (hasSearchConditions) {
        searchReservations(page);
    } else {
        loadReservations(page);
    }
}

// 验证预约码
async function verifyReservation() {
    const code = document.getElementById('verificationCode').value.trim();
    if (!code) {
        showAlert('verificationAlert', '请输入预约码');
        return;
    }
    
    try {
        const response = await apiRequest(`verification.php?action=verify_code&code=${code}`);
        
        if (response.code === 200) {
            currentVerificationData = response.data;
            displayVerificationResult(response.data);
            document.getElementById('checkInBtn').style.display = 'inline-block';
            showAlert('verificationAlert', '预约码验证成功！', 'success');
        } else {
            document.getElementById('verificationResult').style.display = 'none';
            document.getElementById('checkInBtn').style.display = 'none';
            showAlert('verificationAlert', response.message || '验证失败');
        }
    } catch (error) {
        console.error('验证预约码失败:', error);
        showAlert('verificationAlert', '验证请求失败：' + error.message);
    }
}

// 显示验证结果
function displayVerificationResult(data) {
    const resultDiv = document.getElementById('verificationResult');
    
    const companionsHtml = data.companions && data.companions.length > 0 
        ? `<p><strong>同伴信息：</strong></p>
           <ul>${data.companions.map(c => `<li>${c.name} (${c.relationship || '同伴'})</li>`).join('')}</ul>`
        : '';
    
    resultDiv.innerHTML = `
        <h4>预约信息</h4>
        <p><strong>预约码：</strong>${data.reservation_code}</p>
        <p><strong>参观者：</strong>${data.visitor_name}</p>
        <p><strong>联系电话：</strong>${data.visitor_phone}</p>
        <p><strong>参观日期：</strong>${data.visit_date}</p>
        <p><strong>参观时段：</strong>${data.slot_name || '全天'} (${data.start_time || ''} - ${data.end_time || ''})</p>
        <p><strong>参观人数：</strong>${data.visitor_count}人</p>
        ${companionsHtml}
        <p><strong>预约状态：</strong><span class="status-badge status-open">${data.status === 'confirmed' ? '已确认' : data.status}</span></p>
        ${data.check_in_time ? `<p><strong>签到时间：</strong>${data.check_in_time}</p>` : ''}
    `;
    
    resultDiv.style.display = 'block';
}

// 签到
async function checkInReservation() {
    if (!currentVerificationData) {
        showAlert('verificationAlert', '请先验证预约码');
        return;
    }
    
    try {
        const response = await apiRequest('verification.php?action=check_in', {
            method: 'POST',
            body: JSON.stringify({
                reservation_code: currentVerificationData.reservation_code,
                notes: '管理后台签到'
            })
        });
        
        if (response.code === 200) {
            showAlert('verificationAlert', '签到成功！', 'success');
            document.getElementById('verificationCode').value = '';
            document.getElementById('verificationResult').style.display = 'none';
            document.getElementById('checkInBtn').style.display = 'none';
            currentVerificationData = null;
            
            // 刷新最近签到记录
            loadRecentCheckins();
            
        } else {
            showAlert('verificationAlert', response.message || '签到失败');
        }
    } catch (error) {
        console.error('签到失败:', error);
        showAlert('verificationAlert', '签到请求失败：' + error.message);
    }
}

// 加载最近签到记录
async function loadRecentCheckins() {
    try {
        const today = new Date().toISOString().split('T')[0];
        const response = await apiRequest(`verification.php?action=recent_checkins&date=${today}&limit=10`);
        
        if (response.code === 200) {
            const checkins = response.data;
            
            const tbody = document.getElementById('recentCheckinsTable');
            if (checkins.length === 0) {
                tbody.innerHTML = '<tr><td colspan="5" class="loading">今日暂无签到记录</td></tr>';
            } else {
                tbody.innerHTML = checkins.map(checkin => `
                    <tr>
                        <td>${checkin.check_in_time}</td>
                        <td>${checkin.reservation_code}</td>
                        <td>${checkin.visitor_name}</td>
                        <td>${checkin.visitor_count}人</td>
                        <td>${checkin.slot_name || '全天'}</td>
                    </tr>
                `).join('');
            }
        }
    } catch (error) {
        console.error('加载签到记录失败:', error);
        document.getElementById('recentCheckinsTable').innerHTML = 
            '<tr><td colspan="5" class="loading">加载失败</td></tr>';
    }
}

// 模态框相关函数
function showAddTimeSlotModal() {
    document.getElementById('addTimeSlotModal').style.display = 'block';
}

function showAddClosureModal() {
    if (!hasPermission('closures.edit')) {
        showAlert('closuresAlert', '权限不足，无法添加闭馆日期');
        return;
    }
    
    // 初始化月份日期选择器
    initializeMonthlyDayOptions();
    initializeYearlyDayOptions();
    
    document.getElementById('addClosureModal').style.display = 'block';
}

// 切换闭馆类型字段显示
function toggleClosureFields() {
    const closureType = document.getElementById('closureType').value;
    
    // 隐藏所有字段组
    document.getElementById('singleDateGroup').style.display = 'none';
    document.getElementById('dateRangeGroup').style.display = 'none';
    document.getElementById('weeklyGroup').style.display = 'none';
    document.getElementById('monthlyGroup').style.display = 'none';
    document.getElementById('yearlyGroup').style.display = 'none';
    
    // 显示对应的字段组
    switch(closureType) {
        case 'once':
            document.getElementById('singleDateGroup').style.display = 'block';
            break;
        case 'range':
            document.getElementById('dateRangeGroup').style.display = 'block';
            break;
        case 'weekly':
            document.getElementById('weeklyGroup').style.display = 'block';
            break;
        case 'monthly':
            document.getElementById('monthlyGroup').style.display = 'block';
            break;
        case 'yearly':
            document.getElementById('yearlyGroup').style.display = 'block';
            break;
    }
}

// 初始化月份日期选择器
function initializeMonthlyDayOptions() {
    const monthlyDay = document.getElementById('monthlyDay');
    monthlyDay.innerHTML = '<option value="">选择日期</option>';
    
    for (let i = 1; i <= 31; i++) {
        const option = document.createElement('option');
        option.value = i;
        option.textContent = i + '日';
        monthlyDay.appendChild(option);
    }
}

// 初始化年度日期选择器
function initializeYearlyDayOptions() {
    const yearlyDay = document.getElementById('yearlyDay');
    yearlyDay.innerHTML = '<option value="">选择日期</option>';
    
    for (let i = 1; i <= 31; i++) {
        const option = document.createElement('option');
        option.value = i;
        option.textContent = i + '日';
        yearlyDay.appendChild(option);
    }
}

function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
    
    // 清空表单
    if (modalId === 'addTimeSlotModal') {
        document.getElementById('slotName').value = '';
        document.getElementById('startTime').value = '';
        document.getElementById('endTime').value = '';
        document.getElementById('maxVisitors').value = '50';
    } else if (modalId === 'editTimeSlotModal') {
        document.getElementById('editSlotName').value = '';
        document.getElementById('editStartTime').value = '';
        document.getElementById('editEndTime').value = '';
        document.getElementById('editMaxVisitors').value = '';
        document.getElementById('editIsActive').value = '1';
        // 清除隐藏的时段ID
        delete window.currentEditingSlotId;
    } else if (modalId === 'addClosureModal') {
        document.getElementById('closureDate').value = '';
        document.getElementById('closureType').value = 'once';
        document.getElementById('closureReason').value = '';
    } else if (modalId === 'editClosureModal') {
        document.getElementById('editClosureDate').value = '';
        document.getElementById('editClosureType').value = 'once';
        document.getElementById('editClosureReason').value = '';
        document.getElementById('editClosureStatus').value = '1';
        // 清除隐藏的闭馆规则ID
        delete window.currentEditingClosureId;
    } else if (modalId === 'addAdminModal') {
        document.getElementById('adminUsername').value = '';
        document.getElementById('adminPassword').value = '';
        document.getElementById('adminRealName').value = '';
        document.getElementById('adminEmail').value = '';
        document.getElementById('adminRole').value = '';
    } else if (modalId === 'addRoleModal') {
        document.getElementById('roleName').value = '';
        document.getElementById('roleDisplayName').value = '';
        document.getElementById('roleDescription').value = '';
        const checkboxes = document.querySelectorAll('#permissionsCheckbox input[type="checkbox"]');
        checkboxes.forEach(cb => cb.checked = false);
    } else if (modalId === 'editAdminModal') {
        document.getElementById('editAdminUsername').value = '';
        document.getElementById('editAdminRealName').value = '';
        document.getElementById('editAdminEmail').value = '';
        document.getElementById('editAdminRole').value = '';
        document.getElementById('editAdminStatus').value = 'active';
        // 清除隐藏的管理员ID
        delete window.currentEditingAdminId;
    } else if (modalId === 'editRoleModal') {
        document.getElementById('editRoleName').value = '';
        document.getElementById('editRoleDisplayName').value = '';
        document.getElementById('editRoleDescription').value = '';
        document.getElementById('editRoleStatus').value = 'active';
        const checkboxes = document.querySelectorAll('#editPermissionsCheckbox input[type="checkbox"]');
        checkboxes.forEach(cb => cb.checked = false);
        
        // 恢复字段的可编辑状态
        document.getElementById('editRoleDisplayName').disabled = false;
        document.getElementById('editRoleStatus').disabled = false;
        
        // 清除系统角色提示
        const systemNotices = document.querySelectorAll('#editRoleModal small');
        systemNotices.forEach(notice => {
            if (notice.innerHTML.includes('系统角色')) {
                notice.remove();
            }
        });
        
        // 清除隐藏的角色ID
        delete window.currentEditingRoleId;
    } else if (modalId === 'addChapterModal') {
        // 如果是添加篇章模态框，清空图片
        clearChapterImages();
    }
}

// 添加时段
async function addTimeSlot() {
    if (!hasPermission('timeslots.edit')) {
        showAlert('timeslotsAlert', '权限不足，无法添加时段');
        return;
    }
    
    const slotName = document.getElementById('slotName').value.trim();
    const startTime = document.getElementById('startTime').value;
    const endTime = document.getElementById('endTime').value;
    const maxVisitors = document.getElementById('maxVisitors').value;
    
    if (!slotName || !startTime || !endTime || !maxVisitors) {
        alert('请填写完整信息');
        return;
    }
    
    try {
        const response = await apiRequest('museum_config.php?action=add_time_slot', {
            method: 'POST',
            body: JSON.stringify({
                slot_name: slotName,
                start_time: startTime,
                end_time: endTime,
                max_visitors: parseInt(maxVisitors)
            })
        });
        
        if (response.code === 200) {
            showAlert('timeslotsAlert', '时段添加成功！', 'success');
            closeModal('addTimeSlotModal');
            loadTimeSlots();
        } else {
            alert(response.message || '添加失败');
        }
    } catch (error) {
        console.error('添加时段失败:', error);
        alert('添加时段失败：' + error.message);
    }
}

// 编辑时段
async function editTimeSlot(id) {
    try {
        // 获取时段数据
        const response = await apiRequest(`museum_config.php?action=get_time_slots`);
        
        if (response.code === 200) {
            const slots = response.data;
            const slot = slots.find(s => s.id == id);
            
            if (slot) {
                // 填充编辑表单
                document.getElementById('editSlotName').value = slot.slot_name;
                document.getElementById('editStartTime').value = slot.start_time;
                document.getElementById('editEndTime').value = slot.end_time;
                document.getElementById('editMaxVisitors').value = slot.max_visitors;
                document.getElementById('editIsActive').value = slot.is_active;
                
                // 保存当前编辑的时段ID
                window.currentEditingSlotId = id;
                
                // 显示编辑模态框
                document.getElementById('editTimeSlotModal').style.display = 'block';
            } else {
                alert('时段不存在');
            }
        } else {
            alert('获取时段信息失败');
        }
    } catch (error) {
        console.error('获取时段信息失败:', error);
        alert('获取时段信息失败：' + error.message);
    }
}

// 更新时段
async function updateTimeSlot() {
    if (!window.currentEditingSlotId) {
        alert('无效的时段ID');
        return;
    }
    
    const slotName = document.getElementById('editSlotName').value.trim();
    const startTime = document.getElementById('editStartTime').value;
    const endTime = document.getElementById('editEndTime').value;
    const maxVisitors = document.getElementById('editMaxVisitors').value;
    const isActive = document.getElementById('editIsActive').value;
    
    if (!slotName || !startTime || !endTime || !maxVisitors) {
        alert('请填写完整信息');
        return;
    }
    
    try {
        const response = await apiRequest(`museum_config.php?action=update_time_slot&id=${window.currentEditingSlotId}`, {
            method: 'PUT',
            body: JSON.stringify({
                id: window.currentEditingSlotId,
                slot_name: slotName,
                start_time: startTime,
                end_time: endTime,
                max_visitors: parseInt(maxVisitors),
                is_active: parseInt(isActive)
            })
        });
        
        if (response.code === 200) {
            showAlert('timeslotsAlert', '时段更新成功！', 'success');
            closeModal('editTimeSlotModal');
            loadTimeSlots();
        } else {
            alert(response.message || '更新失败');
        }
    } catch (error) {
        console.error('更新时段失败:', error);
        alert('更新时段失败：' + error.message);
    }
}

// 添加管理员
async function addAdmin() {
    const username = document.getElementById('adminUsername').value.trim();
    const password = document.getElementById('adminPassword').value;
    const realName = document.getElementById('adminRealName').value.trim();
    const email = document.getElementById('adminEmail').value.trim();
    const roleId = document.getElementById('adminRole').value;
    
    if (!username || !password || !roleId) {
        alert('请填写必要信息');
        return;
    }
    
    try {
        const response = await apiRequest('admin_management.php?action=create_admin', {
            method: 'POST',
            body: JSON.stringify({
                username,
                password,
                real_name: realName,
                email,
                role_id: parseInt(roleId)
            })
        });
        
        if (response.code === 200) {
            showAlert('adminAlert', '管理员添加成功！', 'success');
            closeModal('addAdminModal');
            loadAdmins();
        } else {
            alert(response.message || '添加失败');
        }
    } catch (error) {
        console.error('添加管理员失败:', error);
        alert('添加管理员失败：' + error.message);
    }
}

// 添加角色
async function addRole() {
    const name = document.getElementById('roleName').value.trim();
    const displayName = document.getElementById('roleDisplayName').value.trim();
    const description = document.getElementById('roleDescription').value.trim();
    
    const selectedPermissions = [];
    const checkboxes = document.querySelectorAll('#permissionsCheckbox input[type="checkbox"]:checked');
    checkboxes.forEach(cb => selectedPermissions.push(cb.value));
    
    if (!name || !displayName) {
        alert('请填写角色名称和显示名称');
        return;
    }
    
    try {
        const response = await apiRequest('admin_management.php?action=create_role', {
            method: 'POST',
            body: JSON.stringify({
                name,
                display_name: displayName,
                description,
                permissions: selectedPermissions
            })
        });
        
        if (response.code === 200) {
            showAlert('rolesAlert', '角色添加成功！', 'success');
            closeModal('addRoleModal');
            loadRoles();
        } else {
            alert(response.message || '添加失败');
        }
    } catch (error) {
        console.error('添加角色失败:', error);
        alert('添加角色失败：' + error.message);
    }
}

// 添加闭馆日期
async function addClosure() {
    if (!hasPermission('closures.edit')) {
        showAlert('closuresAlert', '权限不足，无法添加闭馆日期');
        return;
    }
    
    const closureType = document.getElementById('closureType').value;
    const closureReason = document.getElementById('closureReason').value.trim();
    
    if (!closureReason) {
        alert('请填写闭馆原因');
        return;
    }
    
    let closureData = {
        closure_type: closureType,
        reason: closureReason
    };
    
    // 根据闭馆类型收集不同的数据
    switch(closureType) {
        case 'once':
            const closureDate = document.getElementById('closureDate').value;
            if (!closureDate) {
                alert('请选择闭馆日期');
                return;
            }
            closureData.closure_date = closureDate;
            break;
            
        case 'range':
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            if (!startDate || !endDate) {
                alert('请选择开始和结束日期');
                return;
            }
            if (startDate > endDate) {
                alert('开始日期不能晚于结束日期');
                return;
            }
            closureData.start_date = startDate;
            closureData.end_date = endDate;
            break;
            
        case 'weekly':
            const weekdays = [];
            document.querySelectorAll('input[name="weekdays"]:checked').forEach(cb => {
                weekdays.push(parseInt(cb.value));
            });
            if (weekdays.length === 0) {
                alert('请至少选择一个星期几');
                return;
            }
            closureData.weekdays = weekdays;
            break;
            
        case 'monthly':
            const monthlyDay = document.getElementById('monthlyDay').value;
            if (!monthlyDay) {
                alert('请选择每月闭馆日期');
                return;
            }
            closureData.monthly_day = parseInt(monthlyDay);
            break;
            
        case 'yearly':
            const yearlyMonth = document.getElementById('yearlyMonth').value;
            const yearlyDay = document.getElementById('yearlyDay').value;
            if (!yearlyMonth || !yearlyDay) {
                alert('请选择每年闭馆的月份和日期');
                return;
            }
            closureData.yearly_month = parseInt(yearlyMonth);
            closureData.yearly_day = parseInt(yearlyDay);
            break;
            
        default:
            alert('请选择闭馆类型');
            return;
    }
    
    try {
        const response = await apiRequest('museum_config.php?action=add_closure_rule', {
            method: 'POST',
            body: JSON.stringify(closureData)
        });
        
        if (response.code === 200) {
            showAlert('closuresAlert', '闭馆规则添加成功！', 'success');
            closeModal('addClosureModal');
            loadClosures();
        } else {
            alert(response.message || '添加失败');
        }
    } catch (error) {
        console.error('添加闭馆规则失败:', error);
        alert('添加闭馆规则失败：' + error.message);
    }
}

// 编辑闭馆规则
async function editClosure(id) {
    try {
        // 获取闭馆规则数据
        const response = await apiRequest('museum_config.php?action=get_closure_dates');
        
        if (response.code === 200) {
            const closures = response.data;
            const closure = closures.find(c => c.id == id);
            
            if (closure) {
                // 填充编辑表单
                document.getElementById('editClosureDate').value = closure.closure_date || '';
                document.getElementById('editClosureType').value = closure.closure_type;
                document.getElementById('editClosureReason').value = closure.reason || '';
                document.getElementById('editClosureStatus').value = closure.is_active;
                
                // 保存当前编辑的闭馆规则ID
                window.currentEditingClosureId = id;
                
                // 显示编辑模态框
                document.getElementById('editClosureModal').style.display = 'block';
            } else {
                alert('闭馆规则不存在');
            }
        } else {
            alert('获取闭馆规则信息失败');
        }
    } catch (error) {
        console.error('获取闭馆规则信息失败:', error);
        alert('获取闭馆规则信息失败：' + error.message);
    }
}

// 更新闭馆规则
async function updateClosure() {
    if (!window.currentEditingClosureId) {
        alert('无效的闭馆规则ID');
        return;
    }
    
    const closureDate = document.getElementById('editClosureDate').value;
    const closureReason = document.getElementById('editClosureReason').value.trim();
    const isActive = document.getElementById('editClosureStatus').value;
    
    if (!closureReason) {
        alert('请填写闭馆原因');
        return;
    }
    
    try {
        const response = await apiRequest(`museum_config.php?action=update_closure_rule&id=${window.currentEditingClosureId}`, {
            method: 'PUT',
            body: JSON.stringify({
                id: window.currentEditingClosureId,
                closure_date: closureDate || null,
                reason: closureReason,
                is_active: parseInt(isActive)
            })
        });
        
        if (response.code === 200) {
            showAlert('closuresAlert', '闭馆规则更新成功！', 'success');
            closeModal('editClosureModal');
            loadClosures();
        } else {
            alert(response.message || '更新失败');
        }
    } catch (error) {
        console.error('更新闭馆规则失败:', error);
        alert('更新闭馆规则失败：' + error.message);
    }
}

// 删除时段
async function deleteTimeSlot(id) {
    if (!hasPermission('timeslots.edit')) {
        showAlert('timeslotsAlert', '权限不足，无法删除时段');
        return;
    }
    
    if (!confirm('确定要删除这个时段吗？')) {
        return;
    }
    
    try {
        const response = await apiRequest(`museum_config.php?action=delete_time_slot&id=${id}`, {
            method: 'DELETE'
        });
        
        if (response.code === 200) {
            showAlert('timeslotsAlert', '时段删除成功！', 'success');
            loadTimeSlots();
        } else {
            alert(response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除时段失败:', error);
        alert('删除时段失败：' + error.message);
    }
}

// 删除管理员
async function deleteAdmin(id) {
    if (!hasPermission('admin.edit')) {
        showAlert('adminAlert', '权限不足，无法删除管理员');
        return;
    }
    
    if (!confirm('确定要删除这个管理员吗？')) {
        return;
    }
    
    try {
        const response = await apiRequest(`admin_management.php?action=delete_admin&id=${id}`, {
            method: 'DELETE'
        });
        
        if (response.code === 200) {
            showAlert('adminAlert', '管理员删除成功！', 'success');
            loadAdmins();
        } else {
            alert(response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除管理员失败:', error);
        alert('删除管理员失败：' + error.message);
    }
}

// 删除角色
async function deleteRole(id) {
    if (!hasPermission('roles.edit')) {
        showAlert('rolesAlert', '权限不足，无法删除角色');
        return;
    }
    
    if (!confirm('确定要删除这个角色吗？')) {
        return;
    }
    
    try {
        const response = await apiRequest(`admin_management.php?action=delete_role&id=${id}`, {
            method: 'DELETE'
        });
        
        if (response.code === 200) {
            showAlert('rolesAlert', '角色删除成功！', 'success');
            loadRoles();
        } else {
            alert(response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除角色失败:', error);
        alert('删除角色失败：' + error.message);
    }
}

// 编辑管理员（占位函数）
function editAdmin(id) {
    alert('编辑管理员功能开发中...');
}

// 编辑角色（占位函数）
function editRole(id) {
    alert('编辑角色功能开发中...');
}

// 删除闭馆日期
async function deleteClosure(id) {
    if (!hasPermission('closures.edit')) {
        showAlert('closuresAlert', '权限不足，无法删除闭馆日期');
        return;
    }
    
    if (!confirm('确定要删除这个闭馆日期吗？')) {
        return;
    }
    
    try {
        const response = await apiRequest(`museum_config.php?action=delete_closure_date&id=${id}`, {
            method: 'DELETE'
        });
        
        if (response.code === 200) {
            showAlert('closuresAlert', '闭馆日期删除成功！', 'success');
            loadClosures();
        } else {
            alert(response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除闭馆日期失败:', error);
        alert('删除闭馆日期失败：' + error.message);
    }
}

// 管理员管理功能
async function loadAdmins() {
    try {
        const response = await apiRequest('admin_management.php?action=admins');
        if (response.code === 200) {
            const admins = response.data.data;
            const tbody = document.getElementById('adminTable');
            tbody.innerHTML = admins.map(admin => `
                <tr>
                    <td>${admin.username}</td>
                    <td>${admin.real_name || '-'}</td>
                    <td>${admin.email || '-'}</td>
                    <td>${admin.role_display_name || '-'}</td>
                    <td><span class="status-badge ${admin.status == 'active' ? 'status-open' : 'status-closed'}">${admin.status == 'active' ? '正常' : '禁用'}</span></td>
                    <td>${admin.last_login_time || '从未登录'}</td>
                    <td>
                        <button class="btn btn-primary" onclick="editAdmin(${admin.id})" data-permission="admin.edit">编辑</button>
                        <button class="btn btn-danger" onclick="deleteAdmin(${admin.id})" data-permission="admin.edit">删除</button>
                    </td>
                </tr>
            `).join('');
            
            // 初始化权限控制
            initializePermissions();
        }
    } catch (error) {
        console.error('加载管理员失败:', error);
        document.getElementById('adminTable').innerHTML = '<tr><td colspan="7" class="loading">加载失败</td></tr>';
    }
}

async function loadRoles() {
    try {
        const response = await apiRequest('admin_management.php?action=roles');
        if (response.code === 200) {
            const roles = response.data;
            const tbody = document.getElementById('rolesTable');
            tbody.innerHTML = roles.map(role => `
                <tr>
                    <td>${role.name}</td>
                    <td>${role.display_name}</td>
                    <td>${role.description || '-'}</td>
                    <td>${role.user_count || 0}</td>
                    <td><span class="status-badge ${role.status == 'active' ? 'status-open' : 'status-closed'}">${role.status == 'active' ? '启用' : '禁用'}</span></td>
                    <td>
                        <button class="btn btn-primary" onclick="editRole(${role.id})" data-permission="roles.edit">编辑</button>
                        ${!role.is_system ? `<button class="btn btn-danger" onclick="deleteRole(${role.id})" data-permission="roles.edit">删除</button>` : ''}
                    </td>
                </tr>
            `).join('');
            
            // 更新角色选择框
            const roleSelect = document.getElementById('adminRole');
            roleSelect.innerHTML = '<option value="">选择角色</option>' + 
                roles.filter(role => role.status === 'active').map(role => 
                    `<option value="${role.id}">${role.display_name}</option>`
                ).join('');
            
            // 初始化权限控制
            initializePermissions();
        }
    } catch (error) {
        console.error('加载角色失败:', error);
        document.getElementById('rolesTable').innerHTML = '<tr><td colspan="6" class="loading">加载失败</td></tr>';
    }
}

async function loadPermissions() {
    try {
        const response = await apiRequest('admin_management.php?action=permissions');
        if (response.code === 200) {
            const permissions = response.data;
            const container = document.getElementById('permissionsCheckbox');
            
            let html = '';
            for (const [module, perms] of Object.entries(permissions)) {
                html += `<h4>${module}</h4>`;
                html += perms.map(perm => `
                    <label style="display: block; margin-bottom: 0.5rem;">
                        <input type="checkbox" name="permissions" value="${perm.name}" style="margin-right: 0.5rem;">
                        ${perm.display_name} (${perm.description})
                    </label>
                `).join('');
            }
            container.innerHTML = html;
        }
    } catch (error) {
        console.error('加载权限失败:', error);
    }
}

// 编辑管理员
async function editAdmin(id) {
    try {
        // 获取管理员数据
        const response = await apiRequest('admin_management.php?action=admins');
        
        if (response.code === 200) {
            const admins = response.data.data;
            const admin = admins.find(a => a.id == id);
            
            if (admin) {
                // 填充编辑表单
                document.getElementById('editAdminUsername').value = admin.username;
                document.getElementById('editAdminRealName').value = admin.real_name || '';
                document.getElementById('editAdminEmail').value = admin.email || '';
                document.getElementById('editAdminStatus').value = admin.status;
                
                // 加载角色列表并设置当前角色
                const rolesResponse = await apiRequest('admin_management.php?action=roles');
                if (rolesResponse.code === 200) {
                    const roles = rolesResponse.data;
                    const roleSelect = document.getElementById('editAdminRole');
                    roleSelect.innerHTML = '<option value="">选择角色</option>' + 
                        roles.filter(role => role.status == 'active').map(role => 
                            `<option value="${role.id}" ${role.id == admin.role_id ? 'selected' : ''}>${role.display_name}</option>`
                        ).join('');
                }
                
                // 保存当前编辑的管理员ID
                window.currentEditingAdminId = id;
                
                // 显示编辑模态框
                document.getElementById('editAdminModal').style.display = 'block';
            } else {
                alert('管理员不存在');
            }
        } else {
            alert('获取管理员信息失败');
        }
    } catch (error) {
        console.error('获取管理员信息失败:', error);
        alert('获取管理员信息失败：' + error.message);
    }
}

// 更新管理员
async function updateAdmin() {
    if (!window.currentEditingAdminId) {
        alert('无效的管理员ID');
        return;
    }
    
    const realName = document.getElementById('editAdminRealName').value.trim();
    const email = document.getElementById('editAdminEmail').value.trim();
    const roleId = document.getElementById('editAdminRole').value;
    const status = document.getElementById('editAdminStatus').value;
    
    // 验证邮箱格式
    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        alert('邮箱格式不正确');
        return;
    }
    
    // 添加加载状态
    const updateButton = document.querySelector('#editAdminModal .btn-primary');
    const originalText = updateButton.innerHTML;
    updateButton.innerHTML = '保存中...';
    updateButton.disabled = true;
    
    try {
        const response = await apiRequest(`admin_management.php?action=update_admin`, {
            method: 'PUT',
            body: JSON.stringify({
                id: window.currentEditingAdminId,
                real_name: realName,
                email: email,
                role_id: parseInt(roleId) || null,
                status: status
            })
        });
        
        if (response.code === 200) {
            showAlert('adminAlert', '管理员更新成功！', 'success');
            closeModal('editAdminModal');
            loadAdmins();
        } else {
            alert(response.message || '更新失败');
        }
    } catch (error) {
        console.error('更新管理员失败:', error);
        alert('更新管理员失败：' + error.message);
    } finally {
        // 恢复按钮状态
        updateButton.innerHTML = originalText;
        updateButton.disabled = false;
    }
}

// 编辑角色
async function editRole(id) {
    try {
        // 获取角色数据
        const response = await apiRequest('admin_management.php?action=roles');
        
        if (response.code === 200) {
            const roles = response.data;
            const role = roles.find(r => r.id == id);
            
            if (role) {
                // 填充编辑表单
                document.getElementById('editRoleName').value = role.name;
                document.getElementById('editRoleDisplayName').value = role.display_name;
                document.getElementById('editRoleDescription').value = role.description || '';
                document.getElementById('editRoleStatus').value = role.status;
                
                // 如果是系统角色，禁用某些字段
                const isSystemRole = role.is_system == 1;
                document.getElementById('editRoleDisplayName').disabled = isSystemRole;
                document.getElementById('editRoleStatus').disabled = isSystemRole;
                
                if (isSystemRole) {
                    // 添加系统角色提示
                    const systemNotice = document.createElement('small');
                    systemNotice.style.color = '#666';
                    systemNotice.style.display = 'block';
                    systemNotice.innerHTML = '注：系统角色的显示名称和状态不可修改';
                    document.getElementById('editRoleDisplayName').parentNode.appendChild(systemNotice);
                }
                
                // 加载权限并设置选中状态
                const permissionsResponse = await apiRequest('admin_management.php?action=permissions');
                if (permissionsResponse.code === 200) {
                    const permissions = permissionsResponse.data;
                    const container = document.getElementById('editPermissionsCheckbox');
                    
                    let html = '';
                    for (const [module, perms] of Object.entries(permissions)) {
                        html += `<h4>${module}</h4>`;
                        html += perms.map(perm => {
                            // 权限已经在后端解析好了
                            const rolePermissions = Array.isArray(role.permissions) ? role.permissions : [];
                            const isChecked = rolePermissions.includes(perm.name) ? 'checked' : '';
                            return `
                                <label style="display: block; margin-bottom: 0.5rem;">
                                    <input type="checkbox" name="editPermissions" value="${perm.name}" style="margin-right: 0.5rem;" ${isChecked}>
                                    ${perm.display_name} (${perm.description})
                                </label>
                            `;
                        }).join('');
                    }
                    container.innerHTML = html;
                }
                
                // 保存当前编辑的角色ID
                window.currentEditingRoleId = id;
                
                // 显示编辑模态框
                document.getElementById('editRoleModal').style.display = 'block';
            } else {
                alert('角色不存在');
            }
        } else {
            alert('获取角色信息失败');
        }
    } catch (error) {
        console.error('获取角色信息失败:', error);
        alert('获取角色信息失败：' + error.message);
    }
}

// 更新角色
async function updateRole() {
    if (!window.currentEditingRoleId) {
        alert('无效的角色ID');
        return;
    }
    
    const displayName = document.getElementById('editRoleDisplayName').value.trim();
    const description = document.getElementById('editRoleDescription').value.trim();
    const status = document.getElementById('editRoleStatus').value;
    
    // 获取选中的权限
    const selectedPermissions = [];
    document.querySelectorAll('#editPermissionsCheckbox input[name="editPermissions"]:checked').forEach(cb => {
        selectedPermissions.push(cb.value);
    });
    
    if (!displayName) {
        alert('请填写显示名称');
        return;
    }
    
    // 检查是否为系统角色
    const isSystemRole = document.getElementById('editRoleDisplayName').disabled;
    
    // 添加加载状态
    const updateButton = document.querySelector('#editRoleModal .btn-primary');
    const originalText = updateButton.innerHTML;
    updateButton.innerHTML = '保存中...';
    updateButton.disabled = true;
    
    try {
        // 构建更新数据
        const updateData = {
            id: window.currentEditingRoleId,
            description: description,
            permissions: selectedPermissions
        };
        
        // 只有非系统角色才能修改显示名称和状态
        if (!isSystemRole) {
            updateData.display_name = displayName;
            updateData.status = status;
        }
        
        const response = await apiRequest(`admin_management.php?action=update_role`, {
            method: 'PUT',
            body: JSON.stringify(updateData)
        });
        
        if (response.code === 200) {
            showAlert('rolesAlert', '角色更新成功！', 'success');
            closeModal('editRoleModal');
            loadRoles();
        } else {
            alert(response.message || '更新失败');
        }
    } catch (error) {
        console.error('更新角色失败:', error);
        alert('更新角色失败：' + error.message);
    } finally {
        // 恢复按钮状态
        updateButton.innerHTML = originalText;
        updateButton.disabled = false;
    }
}

async function loadLogs() {
    const logType = document.getElementById('logType').value;
    try {
        const action = logType === 'login' ? 'login_logs' : 'operation_logs';
        const response = await apiRequest(`admin_management.php?action=${action}`);
        
        if (response.code === 200) {
            const logs = response.data;
            const tbody = document.getElementById('logsTable');
            const thead = document.getElementById('logsTableHead');
            
            // 根据日志类型调整表头
            if (logType === 'login') {
                thead.innerHTML = `
                    <tr>
                        <th>登录时间</th>
                        <th>用户名</th>
                        <th>登录状态</th>
                        <th>IP地址</th>
                        <th>详情</th>
                    </tr>
                `;
                
                tbody.innerHTML = logs.map(log => `
                    <tr>
                        <td>${log.created_at}</td>
                        <td>${log.username}</td>
                        <td><span class="status-badge ${log.login_status === 'success' ? 'status-open' : 'status-closed'}">${log.login_status === 'success' ? '成功' : '失败'}</span></td>
                        <td>${log.ip_address}</td>
                        <td>${log.failure_reason || '正常登录'}</td>
                    </tr>
                `).join('');
            } else {
                thead.innerHTML = `
                    <tr>
                        <th>操作时间</th>
                        <th>操作人</th>
                        <th>操作类型</th>
                        <th>操作模块</th>
                        <th>IP地址</th>
                        <th>操作描述</th>
                    </tr>
                `;
                
                tbody.innerHTML = logs.map(log => `
                    <tr>
                        <td>${log.created_at}</td>
                        <td>${log.username || '未知'}</td>
                        <td><span class="status-badge status-open">${log.action}</span></td>
                        <td><span class="badge" style="background-color: #6c757d; color: white; padding: 2px 6px; border-radius: 3px; font-size: 12px;">${log.module || '系统'}</span></td>
                        <td>${log.ip_address}</td>
                        <td title="${log.description}">${log.description ? (log.description.length > 50 ? log.description.substring(0, 50) + '...' : log.description) : '-'}</td>
                    </tr>
                `).join('');
            }
            
            if (logs.length === 0) {
                tbody.innerHTML = `<tr><td colspan="${logType === 'login' ? '5' : '6'}" class="loading">暂无${logType === 'login' ? '登录' : '操作'}日志记录</td></tr>`;
            }
        }
    } catch (error) {
        console.error('加载日志失败:', error);
        document.getElementById('logsTable').innerHTML = '<tr><td colspan="6" class="loading">加载失败</td></tr>';
    }
}

// 模态框管理
function showAddAdminModal() {
    if (!hasPermission('admin.edit')) {
        showAlert('adminAlert', '权限不足，无法添加管理员');
        return;
    }
    document.getElementById('addAdminModal').style.display = 'block';
}

function showAddRoleModal() {
    if (!hasPermission('roles.edit')) {
        showAlert('rolesAlert', '权限不足，无法添加角色');
        return;
    }
    loadPermissions();
    document.getElementById('addRoleModal').style.display = 'block';
}

// 点击模态框外部关闭
window.onclick = function(event) {
    const modals = document.querySelectorAll('.modal');
    modals.forEach(modal => {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    });
}

// 用户管理功能
async function loadUsers() {
    try {
        const response = await apiRequest('admin_management.php?action=users');
        if (response.code === 200) {
            const users = response.data;
            const tbody = document.getElementById('usersTable');
            
            if (!users || users.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="loading">暂无微信用户数据</td></tr>';
                return;
            }
            
            tbody.innerHTML = users.map(user => {
                const registerTime = user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '-';
                const reservationCount = user.reservation_count || 0;
                const statusBadge = user.status === 'active' ? 'status-open' : 'status-closed';
                const statusText = user.status === 'active' ? '正常' : '禁用';
                const isVerifier = user.is_verifier === 1;
                const verifierBadge = isVerifier ? '<span class="badge" style="background: #28a745; color: white; font-size: 11px;">核销员</span>' : '';
                
                return `
                    <tr>
                        <td>${user.id}</td>
                        <td>
                            <div style="display: flex; align-items: center;">
                                ${user.avatar_url ? `<img src="${user.avatar_url}" style="width: 24px; height: 24px; border-radius: 50%; margin-right: 8px;" alt="头像">` : ''}
                                <span>${user.nickname || '-'}</span>
                            </div>
                        </td>
                        <td>${user.real_name || '-'}</td>
                        <td>${registerTime}</td>
                        <td><span class="badge" style="background-color: #17a2b8; color: white; padding: 2px 6px; border-radius: 3px; font-size: 12px;">${reservationCount}</span></td>
                        <td>${verifierBadge}</td>
                        <td><span class="status-badge ${statusBadge}">${statusText}</span></td>
                        <td>
                            <button class="btn btn-primary" onclick="viewUserDetail(${user.id})" style="margin-right: 0.5rem; padding: 4px 8px; font-size: 12px;" data-permission="users.view">详情</button>
                            <button class="btn btn-${user.status === 'active' ? 'danger' : 'success'}" onclick="toggleUserStatus(${user.id}, '${user.status}')" style="padding: 4px 8px; font-size: 12px; margin-right: 0.5rem;" data-permission="users.edit">${user.status === 'active' ? '禁用' : '启用'}</button>
                            <button class="btn btn-${isVerifier ? 'warning' : 'info'}" onclick="toggleVerifierStatus(${user.id}, ${isVerifier ? 1 : 0})" style="padding: 4px 8px; font-size: 12px;" data-permission="users.edit">${isVerifier ? '取消核销员' : '设为核销员'}</button>
                        </td>
                    </tr>
                `;
            }).join('');
            
            // 初始化权限控制
            initializePermissions();
        }
    } catch (error) {
        console.error('加载微信用户失败:', error);
        document.getElementById('usersTable').innerHTML = '<tr><td colspan="8" class="loading">加载失败</td></tr>';
        showAlert('usersAlert', '加载微信用户失败：' + error.message);
    }
}

// 搜索用户
async function searchUsers() {
    const searchTerm = document.getElementById('userSearch').value.trim();
    if (!searchTerm) {
        loadUsers();
        return;
    }
    
    try {
        document.getElementById('usersTable').innerHTML = '<tr><td colspan="7" class="loading">搜索中...</td></tr>';
        
        const response = await apiRequest(`admin_management.php?action=search_users&keyword=${encodeURIComponent(searchTerm)}`);
        if (response.code === 200) {
            const users = response.data;
            const tbody = document.getElementById('usersTable');
            
            if (!users || users.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" class="loading">未找到匹配的微信用户</td></tr>';
                return;
            }
            
            tbody.innerHTML = users.map(user => {
                const registerTime = user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '-';
                const reservationCount = user.reservation_count || 0;
                const statusBadge = user.status === 'active' ? 'status-open' : 'status-closed';
                const statusText = user.status === 'active' ? '正常' : '禁用';
                
                return `
                    <tr>
                        <td>${user.id}</td>
                        <td>
                            <div style="display: flex; align-items: center;">
                                ${user.avatar_url ? `<img src="${user.avatar_url}" style="width: 24px; height: 24px; border-radius: 50%; margin-right: 8px;" alt="头像">` : ''}
                                <span>${user.nickname || user.username || '-'}</span>
                            </div>
                        </td>
                        <td>${user.real_name || '-'}</td>
                        <td>${registerTime}</td>
                        <td><span class="badge" style="background-color: #17a2b8; color: white; padding: 2px 6px; border-radius: 3px; font-size: 12px;">${reservationCount}</span></td>
                        <td><span class="status-badge ${statusBadge}">${statusText}</span></td>
                        <td>
                            <button class="btn btn-primary" onclick="viewUserDetail(${user.id})" style="margin-right: 0.5rem; padding: 4px 8px; font-size: 12px;" data-permission="users.view">详情</button>
                            <button class="btn btn-${user.status === 'active' ? 'danger' : 'success'}" onclick="toggleUserStatus(${user.id}, '${user.status}')" style="padding: 4px 8px; font-size: 12px;" data-permission="users.edit">${user.status === 'active' ? '禁用' : '启用'}</button>
                        </td>
                    </tr>
                `;
            }).join('');
            
            
            // 初始化权限控制
            initializePermissions();
        } else {
            showAlert('usersAlert', response.message || '搜索失败');
        }
    } catch (error) {
        console.error('搜索微信用户失败:', error);
        showAlert('usersAlert', '搜索失败：' + error.message);
        document.getElementById('usersTable').innerHTML = '<tr><td colspan="7" class="loading">搜索失败</td></tr>';
    }
}

// 查看用户详情
async function viewUserDetail(userId) {
    try {
        const response = await apiRequest(`admin_management.php?action=user_detail&id=${userId}`);
        if (response.code === 200) {
            const user = response.data;
            
            let detailHtml = `
                <div style="display: flex; align-items: flex-start; margin-bottom: 20px;">
                    ${user.avatar_url ? `<img src="${user.avatar_url}" style="width: 80px; height: 80px; border-radius: 50%; margin-right: 20px;" alt="微信头像">` : '<div style="width: 80px; height: 80px; background: #f0f0f0; border-radius: 50%; margin-right: 20px; display: flex; align-items: center; justify-content: center; color: #999;">无头像</div>'}
                    <div>
                        <h3>${user.real_name || user.nickname || '用户' + user.id}</h3>
                        <p style="margin: 5px 0; color: #666;">微信用户ID: ${user.id}</p>
                        <p style="margin: 5px 0; color: #666;">账户状态: <span style="color: ${user.status === 'active' ? '#28a745' : '#dc3545'};">${user.status === 'active' ? '正常' : '禁用'}</span></p>
                    </div>
                </div>
                
                <h4>基本信息</h4>
                <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9; width: 120px;"><strong>微信昵称:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${user.nickname || user.username || '-'}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>真实姓名:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${user.real_name || '-'}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>手机号:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${user.phone || '-'}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>身份证号:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${user.id_card ? user.id_card.replace(/(\d{6})\d*(\d{4})/, '$1****$2') : '-'}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>注册时间:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${user.created_at || '-'}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>最后更新:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${user.updated_at || '-'}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>预约次数:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;"><span style="background: #17a2b8; color: white; padding: 4px 8px; border-radius: 12px;">${user.reservation_count || 0}</span></td>
                    </tr>
                </table>
                
                ${user.openid ? `
                <h4>微信信息</h4>
                <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9; width: 120px;"><strong>OpenID:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd; font-family: monospace;">${user.openid.substring(0, 10)}...${user.openid.substring(user.openid.length - 6)}</td>
                    </tr>
                    ${user.unionid ? `
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>UnionID:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd; font-family: monospace;">${user.unionid.substring(0, 10)}...${user.unionid.substring(user.unionid.length - 6)}</td>
                    </tr>
                    ` : ''}
                </table>
                ` : ''}
            `;
            
            // 显示最近预约记录
            if (user.recent_reservations && user.recent_reservations.length > 0) {
                detailHtml += `
                    <h4>最近预约记录 (共${user.recent_reservations.length}条)</h4>
                    <table style="width: 100%; border-collapse: collapse;">
                        <thead>
                            <tr style="background: #f8f9fa;">
                                <th style="padding: 8px; border: 1px solid #ddd; text-align: left;">预约码</th>
                                <th style="padding: 8px; border: 1px solid #ddd; text-align: left;">参观日期</th>
                                <th style="padding: 8px; border: 1px solid #ddd; text-align: left;">时段</th>
                                <th style="padding: 8px; border: 1px solid #ddd; text-align: left;">人数</th>
                                <th style="padding: 8px; border: 1px solid #ddd; text-align: left;">状态</th>
                                <th style="padding: 8px; border: 1px solid #ddd; text-align: left;">预约时间</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${user.recent_reservations.map(res => {
                                let statusColor = '';
                                let statusText = '';
                                switch(res.status) {
                                    case 'confirmed':
                                        statusColor = '#28a745';
                                        statusText = '已确认';
                                        break;
                                    case 'checked_in':
                                        statusColor = '#007bff';
                                        statusText = '已签到';
                                        break;
                                    case 'cancelled':
                                        statusColor = '#dc3545';
                                        statusText = '已取消';
                                        break;
                                    case 'expired':
                                        statusColor = '#6c757d';
                                        statusText = '已过期';
                                        break;
                                    default:
                                        statusColor = '#6c757d';
                                        statusText = res.status;
                                }
                                
                                return `
                                    <tr>
                                        <td style="padding: 8px; border: 1px solid #ddd; font-family: monospace;">${res.reservation_code}</td>
                                        <td style="padding: 8px; border: 1px solid #ddd;">${res.visit_date}</td>
                                        <td style="padding: 8px; border: 1px solid #ddd;">${res.slot_name || '全天'}</td>
                                        <td style="padding: 8px; border: 1px solid #ddd;">${res.visitor_count}人</td>
                                        <td style="padding: 8px; border: 1px solid #ddd;"><span style="color: ${statusColor}; font-weight: bold;">${statusText}</span></td>
                                        <td style="padding: 8px; border: 1px solid #ddd;">${res.created_at || '-'}</td>
                                    </tr>
                                `;
                            }).join('')}
                        </tbody>
                    </table>
                `;
            } else {
                detailHtml += `
                    <h4>预约记录</h4>
                    <p style="text-align: center; color: #999; padding: 20px; background: #f8f9fa; border-radius: 5px;">该用户暂无预约记录</p>
                `;
            }
            
            // 打开新窗口显示详情
            const detailWindow = window.open('', '_blank', 'width=800,height=700,scrollbars=yes');
            detailWindow.document.write(`
                <html>
                <head>
                    <title>微信用户详情 - ${user.real_name || user.nickname || '用户' + user.id}</title>
                    <meta charset="UTF-8">
                    <style>
                        body { 
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
                            padding: 20px; 
                            background: #f8f9fa;
                        }
                        .container {
                            max-width: 800px;
                            margin: 0 auto;
                            background: white;
                            padding: 30px;
                            border-radius: 8px;
                            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                        }
                        h3 { color: #2c3e50; margin: 0; }
                        h4 { color: #34495e; margin: 20px 0 10px 0; border-bottom: 2px solid #3498db; padding-bottom: 5px; }
                        table { font-size: 14px; }
                        @media print {
                            body { background: white; }
                            .container { box-shadow: none; }
                        }
                    </style>
                </head>
                <body>
                    <div class="container">
                        ${detailHtml}
                        <div style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; color: #666;">
                            <small>博物馆预约管理系统 - 微信用户详情</small>
                        </div>
                    </div>
                </body>
                </html>
            `);
        } else {
            alert(response.message || '获取微信用户详情失败');
        }
    } catch (error) {
        console.error('获取微信用户详情失败:', error);
        alert('获取微信用户详情失败：' + error.message);
    }
}

// 切换用户状态
async function toggleUserStatus(userId, currentStatus) {
    const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    const action = newStatus === 'active' ? '启用' : '禁用';
    
    if (!confirm(`确定要${action}此用户吗？`)) {
        return;
    }
    
    try {
        const response = await apiRequest('admin_management.php?action=toggle_user_status', {
            method: 'PUT',
            body: JSON.stringify({
                user_id: userId,
                status: newStatus
            })
        });
        
        if (response.code === 200) {
            showAlert('usersAlert', `用户${action}成功！`, 'success');
            loadUsers(); // 重新加载用户列表
        } else {
            alert(response.message || `${action}用户失败`);
        }
    } catch (error) {
        console.error(`${action}用户失败:`, error);
        alert(`${action}用户失败：` + error.message);
    }
}

// 预约管理附加功能

function getStatusText(status) {
    const statusMap = {
        'confirmed': '已确认',
        'pending': '待审核',
        'cancelled': '已取消',
        'completed': '已完成',
        'expired': '已过期',
        'approved': '已批准',
        'rejected': '已拒绝'
    };
    return statusMap[status] || status;
}

// 通过预约码签到
async function checkInReservationById(reservationCode) {
    if (!confirm('确定要为此预约进行签到吗？')) {
        return;
    }
    
    try {
        const response = await apiRequest('verification.php?action=check_in', {
            method: 'POST',
            body: JSON.stringify({
                reservation_code: reservationCode,
                notes: '管理后台签到'
            })
        });
        
        if (response.code === 200) {
            showAlert('reservationsAlert', '签到成功！', 'success');
            // 重新加载预约列表，保持当前页
            goToReservationPage(currentReservationPage);
        } else {
            alert(response.message || '签到失败');
        }
    } catch (error) {
        console.error('签到失败:', error);
        alert('签到失败：' + error.message);
    }
}

// 取消预约
async function cancelReservation(reservationId, reservationType = 'personal') {
    const reason = prompt('请输入取消原因（可选）:');
    if (reason === null) {
        return; // 用户取消了操作
    }
    
    if (!confirm('确定要取消此预约吗？')) {
        return;
    }
    
    try {
        const response = await apiRequest('admin_reservations.php?action=update_status', {
            method: 'POST',
            body: JSON.stringify({
                id: reservationId,
                type: reservationType,
                status: 'cancelled',
                notes: reason || '管理员取消'
            })
        });
        
        if (response.code === 200) {
            showAlert('reservationsAlert', '预约取消成功！', 'success');
            // 重新加载预约列表，保持当前页
            goToReservationPage(currentReservationPage);
        } else {
            alert(response.message || '取消预约失败');
        }
    } catch (error) {
        console.error('取消预约失败:', error);
        alert('取消预约失败：' + error.message);
    }
}

// 活动管理功能
async function loadActivities() {
    try {
        const response = await apiRequest('admin_management.php?action=activities');
        if (response.code === 200) {
            const activities = response.data;
            const tbody = document.getElementById('activitiesTable');
            
            if (!activities || activities.length === 0) {
                tbody.innerHTML = '<tr><td colspan="12" class="loading">暂无活动申请数据</td></tr>';
                return;
            }
            
            tbody.innerHTML = activities.map(activity => {
                let statusBadge = '';
                let statusText = '';
                
                switch(parseInt(activity.status)) {
                    case 0:
                        statusBadge = 'status-pending';
                        statusText = '待审核';
                        break;
                    case 1:
                        statusBadge = 'status-open';
                        statusText = '已通过';
                        break;
                    case 2:
                        statusBadge = 'status-closed';
                        statusText = '已拒绝';
                        break;
                    case 3:
                        statusBadge = 'status-closed';
                        statusText = '已取消';
                        break;
                    default:
                        statusBadge = 'status-pending';
                        statusText = '未知';
                }
                
                const applicantName = activity.applicant_real_name || activity.applicant_nickname || '-';
                const departmentInfo = [activity.department, activity.major].filter(x => x).join('/') || '-';
                const timeRange = `${activity.start_time?.substring(0, 5)} - ${activity.end_time?.substring(0, 5)}`;
                
                return `
                    <tr>
                        <td>${activity.id}</td>
                        <td title="${activity.activity_description || ''}">${activity.activity_name}</td>
                        <td>${activity.activity_type || '-'}</td>
                        <td>${activity.activity_date}</td>
                        <td>${timeRange}</td>
                        <td>${activity.participant_count}人</td>
                        <td>${activity.organizer || '-'}</td>
                        <td>${activity.contact_name || '-'}</td>
                        <td>${activity.contact_phone || '-'}</td>
                        <td><span class="status-badge ${statusBadge}">${statusText}</span></td>
                        <td><small>${new Date(activity.created_at).toLocaleDateString('zh-CN')}</small></td>
                        <td>
                            <button class="btn btn-primary" onclick="viewActivityDetail(${activity.id})" style="margin-right: 0.5rem; padding: 4px 8px; font-size: 12px;" data-permission="activities.view">详情</button>
                            ${parseInt(activity.status) === 0 ? `
                            <button class="btn btn-success" onclick="updateActivityStatus(${activity.id}, 'approved')" style="padding: 4px 8px; font-size: 12px; margin-right: 0.25rem;" data-permission="activities.edit">批准</button>
                            <button class="btn btn-danger" onclick="showRejectActivityModal(${activity.id}, '${activity.activity_name}')" style="padding: 4px 8px; font-size: 12px;" data-permission="activities.edit">拒绝</button>
                            ` : ''}
                            ${parseInt(activity.status) === 1 ? `
                            <button class="btn btn-warning" onclick="updateActivityStatus(${activity.id}, 'completed')" style="padding: 4px 8px; font-size: 12px;" data-permission="activities.edit">完成</button>
                            ` : ''}
                        </td>
                    </tr>
                `;
            }).join('');
            
            // 更新统计数据
            updateActivityStatistics(activities);
            
            // 初始化权限控制
            initializePermissions();
        }
    } catch (error) {
        console.error('加载活动申请失败:', error);
        document.getElementById('activitiesTable').innerHTML = '<tr><td colspan="12" class="loading">加载失败</td></tr>';
        showAlert('activitiesAlert', '加载活动申请失败：' + error.message);
    }
}

// 更新活动统计数据
function updateActivityStatistics(activities) {
    if (!activities || activities.length === 0) {
        document.getElementById('activityTotalCount').textContent = '0';
        document.getElementById('activityPendingCount').textContent = '0';
        document.getElementById('activityApprovedCount').textContent = '0';
        document.getElementById('activityTodayCount').textContent = '0';
        return;
    }
    
    const totalCount = activities.length;
    const pendingCount = activities.filter(a => parseInt(a.status) === 0).length;
    const approvedCount = activities.filter(a => parseInt(a.status) === 1).length;
    
    // 计算今日新增
    const today = new Date().toDateString();
    const todayCount = activities.filter(a => {
        const activityDate = new Date(a.created_at).toDateString();
        return activityDate === today;
    }).length;
    
    document.getElementById('activityTotalCount').textContent = totalCount;
    document.getElementById('activityPendingCount').textContent = pendingCount;
    document.getElementById('activityApprovedCount').textContent = approvedCount;
    document.getElementById('activityTodayCount').textContent = todayCount;
}

// 搜索活动
async function searchActivities() {
    const searchTerm = document.getElementById('activitySearch').value.trim();
    const status = document.getElementById('activityStatusFilter').value;
    const type = document.getElementById('activityTypeFilter').value;
    const date = document.getElementById('activityDateFilter').value;
    
    // 如果所有条件都为空，加载全部数据
    if (!searchTerm && !status && !type && !date) {
        loadActivities();
        return;
    }
    
    try {
        document.getElementById('activitiesTable').innerHTML = '<tr><td colspan="12" class="loading">搜索中...</td></tr>';
        
        // 构建查询参数
        const params = new URLSearchParams();
        params.append('action', 'search_activities');
        
        if (searchTerm) params.append('keyword', searchTerm);
        if (status) params.append('status', status);
        if (type) params.append('type', type);
        if (date) params.append('date', date);
        
        const response = await apiRequest(`admin_management.php?${params.toString()}`);
        if (response.code === 200) {
            const activities = response.data;
            const tbody = document.getElementById('activitiesTable');
            
            if (!activities || activities.length === 0) {
                tbody.innerHTML = '<tr><td colspan="12" class="loading">未找到匹配的活动申请</td></tr>';
                return;
            }
            
            tbody.innerHTML = activities.map(activity => {
                let statusBadge = '';
                let statusText = '';
                
                switch(parseInt(activity.status)) {
                    case 0:
                        statusBadge = 'status-pending';
                        statusText = '待审核';
                        break;
                    case 1:
                        statusBadge = 'status-open';
                        statusText = '已通过';
                        break;
                    case 2:
                        statusBadge = 'status-closed';
                        statusText = '已拒绝';
                        break;
                    case 3:
                        statusBadge = 'status-closed';
                        statusText = '已取消';
                        break;
                    default:
                        statusBadge = 'status-pending';
                        statusText = '未知';
                }
                
                const applicantName = activity.applicant_real_name || activity.applicant_nickname || '-';
                const departmentInfo = [activity.department, activity.major].filter(x => x).join('/') || '-';
                const timeRange = `${activity.start_time?.substring(0, 5)} - ${activity.end_time?.substring(0, 5)}`;
                
                return `
                    <tr>
                        <td>${activity.id}</td>
                        <td title="${activity.activity_description || ''}">${activity.activity_name}</td>
                        <td>${activity.activity_type || '-'}</td>
                        <td>${activity.activity_date}</td>
                        <td>${timeRange}</td>
                        <td>${activity.participant_count}人</td>
                        <td>${activity.organizer || '-'}</td>
                        <td>${activity.contact_name || '-'}</td>
                        <td>${activity.contact_phone || '-'}</td>
                        <td><span class="status-badge ${statusBadge}">${statusText}</span></td>
                        <td><small>${new Date(activity.created_at).toLocaleDateString('zh-CN')}</small></td>
                        <td>
                            <button class="btn btn-primary" onclick="viewActivityDetail(${activity.id})" style="margin-right: 0.5rem; padding: 4px 8px; font-size: 12px;" data-permission="activities.view">详情</button>
                            ${parseInt(activity.status) === 0 ? `
                            <button class="btn btn-success" onclick="updateActivityStatus(${activity.id}, 'approved')" style="padding: 4px 8px; font-size: 12px; margin-right: 0.25rem;" data-permission="activities.edit">批准</button>
                            <button class="btn btn-danger" onclick="showRejectActivityModal(${activity.id}, '${activity.activity_name}')" style="padding: 4px 8px; font-size: 12px;" data-permission="activities.edit">拒绝</button>
                            ` : ''}
                            ${parseInt(activity.status) === 1 ? `
                            <button class="btn btn-warning" onclick="updateActivityStatus(${activity.id}, 'completed')" style="padding: 4px 8px; font-size: 12px;" data-permission="activities.edit">完成</button>
                            ` : ''}
                        </td>
                    </tr>
                `;
            }).join('');
            
            // 更新搜索结果的统计数据
            updateActivityStatistics(activities);
            
            // 初始化权限控制
            initializePermissions();
        } else {
            showAlert('activitiesAlert', response.message || '搜索失败');
        }
    } catch (error) {
        console.error('搜索活动申请失败:', error);
        showAlert('activitiesAlert', '搜索失败：' + error.message);
        document.getElementById('activitiesTable').innerHTML = '<tr><td colspan="12" class="loading">搜索失败</td></tr>';
    }
}

// 按状态筛选活动
function filterActivitiesByStatus() {
    searchActivities(); // 重新执行搜索，会包含所有筛选条件
}

// 按日期筛选活动
function filterActivityByDate() {
    searchActivities(); // 重新执行搜索，会包含所有筛选条件
}

// 按类型筛选活动
function filterActivityByType() {
    searchActivities(); // 重新执行搜索，会包含所有筛选条件
}

// 从状态文本获取状态值
function getStatusFromText(statusText) {
    const statusMap = {
        '待审核': '0',
        '已通过': '1', 
        '已拒绝': '2',
        '已取消': '3'
    };
    return statusMap[statusText] || statusText;
}

// 查看活动详情
async function viewActivityDetail(activityId) {
    try {
        const response = await apiRequest(`admin_management.php?action=activity_detail&id=${activityId}`);
        if (response.code === 200) {
            const activity = response.data;
            
            // 构建自定义字段显示
            let customFieldsHtml = '';
            if (activity.custom_fields && Object.keys(activity.custom_fields).length > 0) {
                customFieldsHtml = `
                    <h4>活动属性</h4>
                    <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
                        ${Object.entries(activity.custom_fields).map(([key, value]) => `
                            <tr>
                                <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9; width: 120px;"><strong>${key}:</strong></td>
                                <td style="padding: 8px; border: 1px solid #ddd;">${value}</td>
                            </tr>
                        `).join('')}
                    </table>
                `;
            }
            
            const detailHtml = `
                <h3>${activity.activity_name}</h3>
                <div style="margin-bottom: 20px; padding: 15px; background: #f8f9fa; border-radius: 5px;">
                    <p><strong>活动状态:</strong> <span style="color: ${parseInt(activity.status) === 1 ? '#28a745' : parseInt(activity.status) === 2 ? '#dc3545' : '#6c757d'};">${getStatusTextFromNumber(activity.status)}</span></p>
                    <p><strong>申请时间:</strong> ${activity.created_at}</p>
                    ${activity.approved_at ? `<p><strong>审核时间:</strong> ${activity.approved_at}</p>` : ''}
                    ${activity.approved_by_name ? `<p><strong>审核人:</strong> ${activity.approved_by_name}</p>` : ''}
                </div>
                
                <h4>基本信息</h4>
                <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9; width: 120px;"><strong>申请人:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${activity.applicant_real_name || activity.applicant_nickname || '-'}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>活动日期:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${activity.activity_date}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>活动时间:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${activity.start_time} - ${activity.end_time}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>参与人数:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;"><span style="background: #17a2b8; color: white; padding: 4px 8px; border-radius: 12px;">${activity.participant_count}人</span></td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>院系:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${activity.department || '-'}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>专业:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${activity.major || '-'}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>班级:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${activity.class_name || '-'}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>联系人:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${activity.contact_name}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>联系电话:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${activity.contact_phone}</td>
                    </tr>
                </table>
                
                ${customFieldsHtml}
                
                <h4>活动描述</h4>
                <div style="padding: 15px; background: #f8f9fa; border-radius: 5px; margin-bottom: 20px;">
                    ${activity.activity_description || '无详细描述'}
                </div>
                
                ${activity.venue_requirements ? `
                <h4>场地需求</h4>
                <div style="padding: 15px; background: #fff3cd; border-radius: 5px; margin-bottom: 20px;">
                    ${activity.venue_requirements}
                </div>
                ` : ''}
                
                ${activity.equipment_needs ? `
                <h4>设备需求</h4>
                <div style="padding: 15px; background: #d4edda; border-radius: 5px; margin-bottom: 20px;">
                    ${activity.equipment_needs}
                </div>
                ` : ''}
                
                ${activity.admin_notes ? `
                <h4>管理员备注</h4>
                <div style="padding: 15px; background: #f8d7da; border-radius: 5px; margin-bottom: 20px;">
                    ${activity.admin_notes}
                </div>
                ` : ''}
            `;
            
            // 打开新窗口显示详情
            const detailWindow = window.open('', '_blank', 'width=900,height=800,scrollbars=yes');
            detailWindow.document.write(`
                <html>
                <head>
                    <title>活动申请详情 - ${activity.activity_name}</title>
                    <meta charset="UTF-8">
                    <style>
                        body { 
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
                            padding: 20px; 
                            background: #f8f9fa;
                            line-height: 1.6;
                        }
                        .container {
                            max-width: 900px;
                            margin: 0 auto;
                            background: white;
                            padding: 30px;
                            border-radius: 8px;
                            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                        }
                        h3 { color: #2c3e50; margin-top: 0; }
                        h4 { color: #34495e; margin: 20px 0 10px 0; border-bottom: 2px solid #3498db; padding-bottom: 5px; }
                        table { font-size: 14px; }
                        @media print {
                            body { background: white; }
                            .container { box-shadow: none; }
                        }
                    </style>
                </head>
                <body>
                    <div class="container">
                        ${detailHtml}
                        <div style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; color: #666;">
                            <small>博物馆活动申请管理系统</small>
                        </div>
                    </div>
                </body>
                </html>
            `);
        } else {
            alert(response.message || '获取活动详情失败');
        }
    } catch (error) {
        console.error('获取活动详情失败:', error);
        alert('获取活动详情失败：' + error.message);
    }
}

// 更新活动状态
async function updateActivityStatus(activityId, newStatus) {
    const statusText = getStatusText(newStatus);
    
    if (!confirm(`确定要将活动状态更改为"${statusText}"吗？`)) {
        return;
    }
    
    try {
        const response = await apiRequest('admin_management.php?action=update_activity_status', {
            method: 'PUT',
            body: JSON.stringify({
                activity_id: activityId,
                status: newStatus,
                admin_notes: ''
            })
        });
        
        if (response.code === 200) {
            showAlert('activitiesAlert', `活动状态更新为"${statusText}"成功！`, 'success');
            loadActivities(); // 重新加载活动列表
        } else {
            alert(response.message || '状态更新失败');
        }
    } catch (error) {
        console.error('更新活动状态失败:', error);
        alert('更新活动状态失败：' + error.message);
    }
}

// 获取状态显示文本
function getStatusText(status) {
    const statusMap = {
        'pending': '待审核',
        'approved': '已批准',
        'rejected': '已拒绝',
        'cancelled': '已取消',
        'completed': '已完成'
    };
    return statusMap[status] || status;
}

// 获取数字状态的中文显示
function getStatusTextFromNumber(status) {
    const statusMap = {
        0: '待审核',
        1: '已通过',
        2: '已拒绝',
        3: '已取消'
    };
    return statusMap[parseInt(status)] || '未知状态';
}

// 显示拒绝活动模态框
let currentRejectActivityId = null;

function showRejectActivityModal(activityId, activityName) {
    currentRejectActivityId = activityId;
    document.getElementById('rejectActivityName').textContent = activityName;
    document.getElementById('rejectReason').value = '';
    document.getElementById('activityRejectModal').style.display = 'block';
}

// 确认拒绝活动
async function confirmRejectActivity() {
    const reason = document.getElementById('rejectReason').value.trim();
    
    if (!reason) {
        alert('请输入拒绝理由');
        return;
    }
    
    if (!currentRejectActivityId) {
        alert('未选择要拒绝的活动');
        return;
    }
    
    try {
        const response = await apiRequest('admin_management.php?action=update_activity_status', {
            method: 'PUT',
            body: JSON.stringify({
                activity_id: currentRejectActivityId,
                status: 'rejected',
                admin_notes: reason
            })
        });
        
        if (response.code === 200) {
            showAlert('activitiesAlert', '活动申请已拒绝', 'success');
            closeModal('activityRejectModal');
            loadActivities(); // 重新加载活动列表
        } else {
            alert(response.message || '拒绝失败');
        }
    } catch (error) {
        console.error('拒绝活动失败:', error);
        alert('拒绝活动失败：' + error.message);
    }
}

// 切换侧边栏显示（移动端）
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    sidebar.classList.toggle('active');
}

// 讲解员管理功能
async function loadVolunteers() {
    try {
        console.log('开始加载讲解员申请数据...');
        
        const tableBody = document.getElementById('volunteersTable');
        if (!tableBody) {
            console.error('无法找到讲解员申请表格元素 #volunteersTable');
            console.log('当前页面上的所有表格元素:', document.querySelectorAll('tbody'));
            return;
        }
        
        console.log('找到表格元素:', tableBody);
        
        tableBody.innerHTML = '<tr><td colspan="9" class="loading">加载中...</td></tr>';
        
        console.log('发送API请求到:', 'admin/volunteer_management.php?action=list');
        const response = await apiRequest('admin/volunteer_management.php?action=list');
        console.log('API响应:', response);
        
        if (response.code === 200 && response.data) {
            const volunteers = response.data.list || [];
            
            if (volunteers.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="9" class="loading">暂无讲解员申请数据</td></tr>';
                updateVolunteerStatistics([]);
                return;
            }
            
            tableBody.innerHTML = volunteers.map(volunteer => {
                const genderText = volunteer.gender === 'male' ? '男' : '女';
                
                // 优化时间显示格式
                const createdDate = new Date(volunteer.created_at);
                const now = new Date();
                const diffTime = now - createdDate;
                const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
                
                let timeDisplay;
                if (diffDays === 0) {
                    timeDisplay = createdDate.toLocaleString('zh-CN', {
                        hour: '2-digit',
                        minute: '2-digit',
                        hour12: false
                    }) + ' 今天';
                } else if (diffDays === 1) {
                    timeDisplay = createdDate.toLocaleString('zh-CN', {
                        hour: '2-digit',
                        minute: '2-digit',
                        hour12: false
                    }) + ' 昨天';
                } else if (diffDays < 30) {
                    timeDisplay = `${diffDays}天前`;
                } else {
                    timeDisplay = createdDate.toLocaleString('zh-CN', {
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit',
                        hour12: false
                    });
                }
                
                // 经验截断显示
                const experienceDisplay = volunteer.experience ? 
                    (volunteer.experience.length > 20 ? volunteer.experience.substring(0, 20) + '...' : volunteer.experience) : 
                    '-';
                
                return `
                    <tr>
                        <td><strong>#${volunteer.id}</strong></td>
                        <td><strong>${volunteer.name}</strong></td>
                        <td>${genderText}</td>
                        <td>${volunteer.phone}</td>
                        <td>${volunteer.student_id || '-'}</td>
                        <td title="${volunteer.department || '-'}">${(volunteer.department || '-').length > 15 ? (volunteer.department || '-').substring(0, 15) + '...' : (volunteer.department || '-')}</td>
                        <td>${volunteer.grade || '-'}</td>
                        <td title="${volunteer.experience || '-'}">${experienceDisplay}</td>
                        <td title="${createdDate.toLocaleString('zh-CN')}">${timeDisplay}</td>
                    </tr>
                `;
            }).join('');
            
            updateVolunteerStatistics(volunteers);
        }
    } catch (error) {
        console.error('加载讲解员申请失败:', error);
        document.getElementById('volunteersTable').innerHTML = '<tr><td colspan="9" class="loading">加载失败</td></tr>';
        showAlert('volunteersAlert', '加载讲解员申请失败：' + error.message);
    }
}

// 更新讲解员统计数据
function updateVolunteerStatistics(volunteers) {
    if (!volunteers || volunteers.length === 0) {
        document.getElementById('volunteerTotalCount').textContent = '0';
        document.getElementById('volunteerTodayCount').textContent = '0';
        document.getElementById('volunteerThisMonthCount').textContent = '0';
        document.getElementById('volunteerRecentCount').textContent = '0';
        return;
    }
    
    const totalCount = volunteers.length;
    const today = new Date();
    const todayStr = today.toDateString();
    
    // 今日新增
    const todayCount = volunteers.filter(v => {
        const createdDate = new Date(v.created_at);
        return createdDate.toDateString() === todayStr;
    }).length;
    
    // 本月申请
    const thisMonthCount = volunteers.filter(v => {
        const createdDate = new Date(v.created_at);
        return createdDate.getFullYear() === today.getFullYear() && 
               createdDate.getMonth() === today.getMonth();
    }).length;
    
    // 近7天
    const sevenDaysAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
    const recentCount = volunteers.filter(v => {
        const createdDate = new Date(v.created_at);
        return createdDate >= sevenDaysAgo;
    }).length;
    
    document.getElementById('volunteerTotalCount').textContent = totalCount;
    document.getElementById('volunteerTodayCount').textContent = todayCount;
    document.getElementById('volunteerThisMonthCount').textContent = thisMonthCount;
    document.getElementById('volunteerRecentCount').textContent = recentCount;
}


// 面试邀约
async function inviteInterview(id) {
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <h3>面试邀约</h3>
                <span class="close" onclick="this.closest('.modal').style.display='none'">&times;</span>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>面试时间：</label>
                    <input type="datetime-local" id="interviewTime" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>面试地点：</label>
                    <input type="text" id="interviewLocation" class="form-control" placeholder="请输入面试地点" required>
                </div>
                <div class="form-group">
                    <label>面试官：</label>
                    <input type="text" id="interviewer" class="form-control" placeholder="请输入面试官姓名" required>
                </div>
                <div class="form-group">
                    <label>面试要求：</label>
                    <textarea id="interviewRequirements" class="form-control" rows="3" placeholder="请输入面试要求和注意事项"></textarea>
                </div>
                <div class="form-group">
                    <label>联系电话：</label>
                    <input type="text" id="contactPhone" class="form-control" placeholder="面试联系电话">
                </div>
            </div>
            <div class="modal-footer">
                <button onclick="sendInterviewInvitation(${id})" class="btn btn-success">发送面试邀约</button>
                <button onclick="this.closest('.modal').style.display='none'" class="btn btn-secondary">取消</button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

// 发送面试邀约
async function sendInterviewInvitation(id) {
    const interviewTime = document.getElementById('interviewTime').value;
    const interviewLocation = document.getElementById('interviewLocation').value.trim();
    const interviewer = document.getElementById('interviewer').value.trim();
    const interviewRequirements = document.getElementById('interviewRequirements').value.trim();
    const contactPhone = document.getElementById('contactPhone').value.trim();
    
    if (!interviewTime || !interviewLocation || !interviewer) {
        showAlert('volunteersAlert', '请填写完整的面试信息');
        return;
    }
    
    try {
        const response = await apiRequest('admin/volunteer_management.php?action=invite_interview', {
            method: 'POST',
            body: JSON.stringify({
                id: id,
                interview_time: interviewTime,
                interview_location: interviewLocation,
                interviewer: interviewer,
                requirements: interviewRequirements,
                contact_phone: contactPhone
            })
        });
        
        if (response.code === 200) {
            showAlert('volunteersAlert', '面试邀约已发送', 'success');
            loadVolunteers();
            document.querySelectorAll('.modal').forEach(modal => modal.style.display='none');
        } else {
            showAlert('volunteersAlert', response.message || '发送失败');
        }
    } catch (error) {
        console.error('发送面试邀约失败:', error);
        showAlert('volunteersAlert', '发送失败：' + error.message);
    }
}

// 查看拒绝原因
async function viewRejectReason(id) {
    try {
        const response = await apiRequest(`admin/volunteer_management.php?action=detail&id=${id}`);
        
        if (response.code === 200 && response.data) {
            const volunteer = response.data;
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.style.display = 'block';
            modal.innerHTML = `
                <div class="modal-content" style="max-width: 500px;">
                    <div class="modal-header">
                        <h3>拒绝原因</h3>
                        <span class="close" onclick="this.closest('.modal').style.display='none'">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label>申请人：</label>
                            <p><strong>${volunteer.name}</strong></p>
                        </div>
                        <div class="form-group">
                            <label>拒绝原因：</label>
                            <div style="background: #f8f9fa; padding: 1rem; border-radius: 4px; min-height: 60px;">
                                ${volunteer.review_note || '无具体原因说明'}
                            </div>
                        </div>
                        <div class="form-group">
                            <label>拒绝时间：</label>
                            <p>${volunteer.updated_at ? new Date(volunteer.updated_at).toLocaleString('zh-CN') : '-'}</p>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button onclick="this.closest('.modal').style.display='none'" class="btn btn-secondary">关闭</button>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        }
    } catch (error) {
        console.error('获取拒绝原因失败:', error);
        showAlert('volunteersAlert', '获取失败：' + error.message);
    }
}

// 拒绝讲解员申请
async function rejectVolunteer(id, reason = '') {
    try {
        const response = await apiRequest('admin/volunteer_management.php?action=reject', {
            method: 'POST',
            body: JSON.stringify({ 
                id: id,
                reason: reason || '不符合要求'
            })
        });
        
        if (response.code === 200) {
            showAlert('volunteersAlert', '申请已拒绝', 'success');
            loadVolunteers();
            // 关闭所有相关模态框
            document.querySelectorAll('.modal').forEach(modal => modal.style.display='none');
        } else {
            showAlert('volunteersAlert', response.message || '操作失败');
        }
    } catch (error) {
        console.error('拒绝申请失败:', error);
        showAlert('volunteersAlert', '操作失败：' + error.message);
    }
}

// 显示拒绝原因模态框
function showRejectModal(id) {
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header">
                <h3>拒绝申请</h3>
                <span class="close" onclick="this.closest('.modal').style.display='none'">&times;</span>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>拒绝原因：</label>
                    <textarea id="rejectReason" placeholder="请输入拒绝原因..." rows="3"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button onclick="rejectVolunteer(${id}, document.getElementById('rejectReason').value)" class="btn btn-danger">确认拒绝</button>
                <button onclick="this.closest('.modal').style.display='none'" class="btn btn-secondary">取消</button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

// 意见反馈管理功能
async function loadFeedbacks() {
    try {
        console.log('开始加载意见反馈数据...');
        
        const tableBody = document.getElementById('feedbackTable');
        if (!tableBody) {
            console.error('无法找到意见反馈表格元素');
            return;
        }
        
        tableBody.innerHTML = '<tr><td colspan="7" class="loading">加载中...</td></tr>';
        
        const response = await apiRequest('admin/feedback_management.php?action=list');
        
        if (response.code === 200 && response.data) {
            const feedbacks = response.data.list || [];
            
            if (feedbacks.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="7" class="loading">暂无意见反馈数据</td></tr>';
                updateFeedbackStatistics([]);
                return;
            }
            
            tableBody.innerHTML = feedbacks.map(feedback => {
                // 优化时间显示格式
                const createdDate = new Date(feedback.created_at);
                const now = new Date();
                const diffTime = now - createdDate;
                const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
                
                let timeDisplay;
                if (diffDays === 0) {
                    timeDisplay = createdDate.toLocaleString('zh-CN', {
                        hour: '2-digit',
                        minute: '2-digit',
                        hour12: false
                    }) + ' 今天';
                } else if (diffDays === 1) {
                    timeDisplay = createdDate.toLocaleString('zh-CN', {
                        hour: '2-digit',
                        minute: '2-digit',
                        hour12: false
                    }) + ' 昨天';
                } else if (diffDays < 30) {
                    timeDisplay = `${diffDays}天前`;
                } else {
                    timeDisplay = createdDate.toLocaleString('zh-CN', {
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit',
                        hour12: false
                    });
                }
                
                // 标题截断显示
                const titleDisplay = feedback.title.length > 25 ? 
                    feedback.title.substring(0, 25) + '...' : 
                    feedback.title;
                
                // 内容截断显示
                const contentDisplay = feedback.content ? 
                    (feedback.content.length > 40 ? feedback.content.substring(0, 40) + '...' : feedback.content) :
                    '-';
                
                return `
                    <tr>
                        <td><strong>#${feedback.id}</strong></td>
                        <td><span class="badge badge-info">${feedback.feedback_type}</span></td>
                        <td title="${feedback.title}"><strong>${titleDisplay}</strong></td>
                        <td>${feedback.user_name || '<em>匿名用户</em>'}</td>
                        <td>${feedback.contact_phone || '-'}</td>
                        <td title="${feedback.content}" style="font-size: 0.9em; color: #666;">${contentDisplay}</td>
                        <td title="${createdDate.toLocaleString('zh-CN')}">${timeDisplay}</td>
                    </tr>
                `;
            }).join('');
            
            updateFeedbackStatistics(feedbacks);
        }
    } catch (error) {
        console.error('加载意见反馈失败:', error);
        document.getElementById('feedbackTable').innerHTML = '<tr><td colspan="7" class="loading">加载失败</td></tr>';
        showAlert('feedbackAlert', '加载意见反馈失败：' + error.message);
    }
}

// 更新意见反馈统计数据
function updateFeedbackStatistics(feedbacks) {
    if (!feedbacks || feedbacks.length === 0) {
        document.getElementById('feedbackTotalCount').textContent = '0';
        document.getElementById('feedbackTodayCount').textContent = '0';
        document.getElementById('feedbackThisMonthCount').textContent = '0';
        document.getElementById('feedbackRecentCount').textContent = '0';
        return;
    }
    
    const totalCount = feedbacks.length;
    const today = new Date();
    const todayStr = today.toDateString();
    
    // 今日新增
    const todayCount = feedbacks.filter(f => {
        const createdDate = new Date(f.created_at);
        return createdDate.toDateString() === todayStr;
    }).length;
    
    // 本月反馈
    const thisMonthCount = feedbacks.filter(f => {
        const createdDate = new Date(f.created_at);
        return createdDate.getFullYear() === today.getFullYear() && 
               createdDate.getMonth() === today.getMonth();
    }).length;
    
    // 近7天
    const sevenDaysAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
    const recentCount = feedbacks.filter(f => {
        const createdDate = new Date(f.created_at);
        return createdDate >= sevenDaysAgo;
    }).length;
    
    document.getElementById('feedbackTotalCount').textContent = totalCount;
    document.getElementById('feedbackTodayCount').textContent = todayCount;
    document.getElementById('feedbackThisMonthCount').textContent = thisMonthCount;
    document.getElementById('feedbackRecentCount').textContent = recentCount;
}


// 快速回复反馈
async function quickReplyFeedback(id) {
    // 首先获取反馈详情
    try {
        const response = await apiRequest(`admin/feedback_management.php?action=detail&id=${id}`);
        
        if (response.code === 200 && response.data) {
            const feedback = response.data;
            
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.style.display = 'block';
            modal.innerHTML = `
                <div class="modal-content" style="max-width: 700px;">
                    <div class="modal-header">
                        <h3>回复意见反馈</h3>
                        <span class="close" onclick="this.closest('.modal').style.display='none'">&times;</span>
                    </div>
                    <div class="modal-body">
                        <!-- 反馈信息 -->
                        <div style="background: #f8f9fa; padding: 1rem; border-radius: 4px; margin-bottom: 1rem;">
                            <h5>反馈内容：</h5>
                            <p><strong>标题：</strong>${feedback.title}</p>
                            <p><strong>类型：</strong>${feedback.feedback_type}</p>
                            <p><strong>用户：</strong>${feedback.user_name || '匿名用户'}</p>
                            <p><strong>内容：</strong></p>
                            <div style="background: white; padding: 0.5rem; border-radius: 3px;">
                                ${feedback.content}
                            </div>
                        </div>
                        
                        <!-- 回复表单 -->
                        <div class="form-group">
                            <label>回复内容：</label>
                            <textarea id="quickReplyContent" class="form-control" placeholder="请输入回复内容..." rows="4" required></textarea>
                        </div>
                        <div class="form-group">
                            <label>处理状态：</label>
                            <select id="feedbackStatus" class="form-control">
                                <option value="processed">已处理</option>
                                <option value="pending">待处理</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button onclick="submitQuickReply(${id})" class="btn btn-primary">发送回复并更新状态</button>
                        <button onclick="this.closest('.modal').style.display='none'" class="btn btn-secondary">取消</button>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        }
    } catch (error) {
        console.error('获取反馈详情失败:', error);
        showAlert('feedbackAlert', '获取详情失败：' + error.message);
    }
}

// 查看反馈回复
async function viewFeedbackReply(id) {
    try {
        const response = await apiRequest(`admin/feedback_management.php?action=detail&id=${id}`);
        
        if (response.code === 200 && response.data) {
            const feedback = response.data;
            
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.style.display = 'block';
            modal.innerHTML = `
                <div class="modal-content" style="max-width: 600px;">
                    <div class="modal-header">
                        <h3>查看回复</h3>
                        <span class="close" onclick="this.closest('.modal').style.display='none'">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label>反馈标题：</label>
                            <p><strong>${feedback.title}</strong></p>
                        </div>
                        <div class="form-group">
                            <label>反馈内容：</label>
                            <div style="background: #f8f9fa; padding: 1rem; border-radius: 4px;">
                                ${feedback.content}
                            </div>
                        </div>
                        <div class="form-group">
                            <label>回复内容：</label>
                            <div style="background: #e8f5e8; padding: 1rem; border-radius: 4px; border-left: 4px solid #28a745;">
                                ${feedback.reply || '暂无回复'}
                            </div>
                        </div>
                        <div class="form-group">
                            <label>回复时间：</label>
                            <p>${feedback.updated_at ? new Date(feedback.updated_at).toLocaleString('zh-CN') : '-'}</p>
                        </div>
                    </div>
                    <div class="modal-footer">
                        ${feedback.status === 'pending' ? `
                            <button onclick="quickReplyFeedback(${id})" class="btn btn-primary">修改回复</button>
                        ` : ''}
                        <button onclick="this.closest('.modal').style.display='none'" class="btn btn-secondary">关闭</button>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        }
    } catch (error) {
        console.error('获取回复详情失败:', error);
        showAlert('feedbackAlert', '获取详情失败：' + error.message);
    }
}

// 提交快速回复
async function submitQuickReply(id) {
    const replyContent = document.getElementById('quickReplyContent').value.trim();
    const status = document.getElementById('feedbackStatus').value;
    
    if (!replyContent) {
        showAlert('feedbackAlert', '请输入回复内容');
        return;
    }
    
    try {
        const response = await apiRequest('admin/feedback_management.php?action=reply', {
            method: 'POST',
            body: JSON.stringify({ 
                id: id,
                reply: replyContent,
                status: status
            })
        });
        
        if (response.code === 200) {
            showAlert('feedbackAlert', '回复成功', 'success');
            loadFeedbacks();
            document.querySelectorAll('.modal').forEach(modal => modal.style.display='none');
        } else {
            showAlert('feedbackAlert', response.message || '回复失败');
        }
    } catch (error) {
        console.error('回复失败:', error);
        showAlert('feedbackAlert', '回复失败：' + error.message);
    }
}

// 提交回复
async function submitReply(id) {
    const replyContent = document.getElementById('replyContent').value.trim();
    
    if (!replyContent) {
        showAlert('feedbackAlert', '请输入回复内容');
        return;
    }
    
    try {
        const response = await apiRequest('admin/feedback_management.php?action=reply', {
            method: 'POST',
            body: JSON.stringify({ 
                id: id,
                reply: replyContent
            })
        });
        
        if (response.code === 200) {
            showAlert('feedbackAlert', '回复成功', 'success');
            loadFeedbacks();
            // 关闭所有相关模态框
            document.querySelectorAll('.modal').forEach(modal => modal.style.display='none');
        } else {
            showAlert('feedbackAlert', response.message || '回复失败');
        }
    } catch (error) {
        console.error('回复失败:', error);
        showAlert('feedbackAlert', '回复失败：' + error.message);
    }
}

// 确认删除意见反馈
function confirmDeleteFeedback(id) {
    if (confirm('确定要删除这条意见反馈吗？此操作不可恢复。')) {
        deleteFeedback(id);
    }
}

// 删除意见反馈
async function deleteFeedback(id) {
    
    try {
        const response = await apiRequest(`admin/feedback_management.php?action=delete&id=${id}`, {
            method: 'DELETE'
        });
        
        if (response.code === 200) {
            showAlert('feedbackAlert', '删除成功', 'success');
            loadFeedbacks();
        } else {
            showAlert('feedbackAlert', response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除失败:', error);
        showAlert('feedbackAlert', '删除失败：' + error.message);
    }
}

// 搜索意见反馈
function searchFeedback() {
    const searchTerm = document.getElementById('feedbackSearch').value.trim();
    const typeFilter = document.getElementById('feedbackTypeFilter').value;
    const dateFilter = document.getElementById('feedbackDateFilter').value;
    
    console.log('搜索参数:', { searchTerm, typeFilter, dateFilter });
    
    // 重新加载数据时会应用搜索条件
    loadFeedbacks();
}

// 搜索志愿者
function searchVolunteers() {
    const searchTerm = document.getElementById('volunteerSearch').value.trim();
    const genderFilter = document.getElementById('volunteerGenderFilter').value;
    const deptFilter = document.getElementById('volunteerDeptFilter').value.trim();
    const dateFilter = document.getElementById('volunteerDateFilter').value;
    
    console.log('搜索参数:', { searchTerm, genderFilter, deptFilter, dateFilter });
    
    // 重新加载数据时会应用搜索条件
    loadVolunteers();
}

// 团队预约分页相关变量
let currentTeamReservationPage = 1;
let teamReservationPageSize = 20;
let totalTeamReservationPages = 0;
let totalTeamReservationCount = 0;

// 团队预约管理功能
async function loadTeamReservations(page = 1) {
    try {
        console.log('开始加载团队预约数据...');
        currentTeamReservationPage = page;
        
        const tableBody = document.getElementById('teamReservationsTable');
        if (!tableBody) {
            console.error('无法找到团队预约表格元素');
            return;
        }
        
        tableBody.innerHTML = '<tr><td colspan="12" class="loading">加载中...</td></tr>';
        
        const response = await apiRequest(`team_reservations.php?action=list&page=${page}&limit=${teamReservationPageSize}`);
        
        console.log('API响应:', response);
        
        if (response.code === 200) {
            const teamReservations = response.data.list || response.data;
            const pagination = response.data.pagination;
            
            console.log('团队预约数据:', teamReservations);
            
            displayTeamReservations(teamReservations);
            
            if (pagination) {
                updateTeamReservationPagination(pagination);
            }
        } else {
            console.error('API错误:', response);
            const tableBody = document.getElementById('teamReservationsTable');
            if (tableBody) {
                tableBody.innerHTML = '<tr><td colspan="12" class="loading">加载失败: ' + (response.message || '未知错误') + '</td></tr>';
            }
        }
    } catch (error) {
        console.error('加载团队预约失败:', error);
        const tableBody = document.getElementById('teamReservationsTable');
        if (tableBody) {
            tableBody.innerHTML = '<tr><td colspan="12" class="loading">加载失败: ' + error.message + '</td></tr>';
        }
        showAlert('teamReservationsAlert', '加载团队预约失败：' + error.message);
    }
}

// 显示团队预约列表
function displayTeamReservations(teamReservations) {
    const tbody = document.getElementById('teamReservationsTable');
    
    if (!tbody) {
        console.error('无法找到团队预约表格元素');
        return;
    }
    
    if (!teamReservations || teamReservations.length === 0) {
        tbody.innerHTML = '<tr><td colspan="12" class="loading">暂无团队预约数据</td></tr>';
        return;
    }

    tbody.innerHTML = teamReservations.map(reservation => {
        let statusBadge = '';
        let statusText = '';
        
        switch(reservation.status) {
            case 'pending':
                statusBadge = 'status-pending';
                statusText = '待审核';
                break;
            case 'approved':
                statusBadge = 'status-open';
                statusText = '已批准';
                break;
            case 'rejected':
                statusBadge = 'status-closed';
                statusText = '已拒绝';
                break;
            case 'cancelled':
                statusBadge = 'status-closed';
                statusText = '已取消';
                break;
            case 'completed':
                statusBadge = 'status-open';
                statusText = '已完成';
                break;
            default:
                statusBadge = 'status-pending';
                statusText = reservation.status;
        }
        
        const needGuideText = reservation.need_guide == 1 ? '需要' : '不需要';
        const timeDisplay = reservation.reservation_time && reservation.end_time ? 
            `${reservation.reservation_time.substring(0, 5)} - ${reservation.end_time.substring(0, 5)}` :
            reservation.reservation_time ? reservation.reservation_time.substring(0, 5) : '未设置';
        
        return `
            <tr>
                <td>${reservation.id}</td>
                <td title="${reservation.team_name}">${reservation.team_name}</td>
                <td>${reservation.contact_name}</td>
                <td title="${reservation.contact_unit || ''}">${reservation.contact_unit && reservation.contact_unit.length > 15 ? reservation.contact_unit.substring(0, 15) + '...' : (reservation.contact_unit || '')}</td>
                <td>${reservation.contact_phone}</td>
                <td><span class="badge" style="background-color: #6c757d; color: white; padding: 2px 6px; border-radius: 3px; font-size: 12px;">${reservation.visitor_identity}</span></td>
                <td>${reservation.reservation_date}</td>
                <td>${timeDisplay}</td>
                <td>${reservation.visitor_count}人</td>
                <td><span class="badge" style="background-color: ${reservation.need_guide == 1 ? '#17a2b8' : '#6c757d'}; color: white; padding: 2px 6px; border-radius: 3px; font-size: 12px;">${needGuideText}</span></td>
                <td><span class="status-badge ${statusBadge}">${statusText}</span></td>
                <td>
                    ${reservation.status === 'pending' ? `
                    <button class="btn btn-primary" onclick="reviewTeamReservation(${reservation.id})" style="padding: 4px 8px; font-size: 12px; margin-right: 0.25rem;" data-permission="reservations.edit">
                        <i class="fas fa-clipboard-check"></i> 审核
                    </button>
                    ` : `
                    <button class="btn btn-info" onclick="viewTeamReservationDetail(${reservation.id})" style="padding: 4px 8px; font-size: 12px; margin-right: 0.25rem;" data-permission="reservations.view">
                        <i class="fas fa-eye"></i> 查看
                    </button>
                    `}
                    ${reservation.status === 'approved' ? `
                    <button class="btn btn-warning" onclick="updateTeamReservationStatus(${reservation.id}, 'completed')" style="padding: 4px 8px; font-size: 12px;" data-permission="reservations.edit">
                        <i class="fas fa-check-circle"></i> 完成
                    </button>
                    ` : ''}
                </td>
            </tr>
        `;
    }).join('');
    
    // 初始化权限控制
    initializePermissions();
}

// 更新团队预约分页控件
function updateTeamReservationPagination(pagination) {
    const paginationDiv = document.getElementById('teamReservationPagination');
    
    if (!paginationDiv) {
        console.error('无法找到团队预约分页元素');
        return;
    }
    
    if (!pagination || pagination.pages <= 1) {
        paginationDiv.innerHTML = '';
        return;
    }
    
    totalTeamReservationPages = pagination.pages;
    totalTeamReservationCount = pagination.total;
    currentTeamReservationPage = pagination.page;
    
    let paginationHtml = `
        <div style="display: flex; align-items: center; justify-content: center; gap: 10px;">
            <span style="color: #666; font-size: 14px;">
                共 ${totalTeamReservationCount} 条记录，第 ${currentTeamReservationPage}/${totalTeamReservationPages} 页
            </span>
            <div style="display: flex; gap: 5px;">
    `;
    
    // 上一页
    if (currentTeamReservationPage > 1) {
        paginationHtml += `
            <button class="btn btn-sm btn-secondary" onclick="goToTeamReservationPage(${currentTeamReservationPage - 1})">
                上一页
            </button>
        `;
    }
    
    // 页码按钮
    let startPage = Math.max(1, currentTeamReservationPage - 2);
    let endPage = Math.min(totalTeamReservationPages, currentTeamReservationPage + 2);
    
    if (startPage > 1) {
        paginationHtml += `<button class="btn btn-sm btn-secondary" onclick="goToTeamReservationPage(1)">1</button>`;
        if (startPage > 2) {
            paginationHtml += `<span style="padding: 0 5px;">...</span>`;
        }
    }
    
    for (let i = startPage; i <= endPage; i++) {
        const activeClass = i === currentTeamReservationPage ? 'btn-primary' : 'btn-secondary';
        paginationHtml += `
            <button class="btn btn-sm ${activeClass}" onclick="goToTeamReservationPage(${i})">${i}</button>
        `;
    }
    
    if (endPage < totalTeamReservationPages) {
        if (endPage < totalTeamReservationPages - 1) {
            paginationHtml += `<span style="padding: 0 5px;">...</span>`;
        }
        paginationHtml += `
            <button class="btn btn-sm btn-secondary" onclick="goToTeamReservationPage(${totalTeamReservationPages})">
                ${totalTeamReservationPages}
            </button>
        `;
    }
    
    // 下一页
    if (currentTeamReservationPage < totalTeamReservationPages) {
        paginationHtml += `
            <button class="btn btn-sm btn-secondary" onclick="goToTeamReservationPage(${currentTeamReservationPage + 1})">
                下一页
            </button>
        `;
    }
    
    paginationHtml += `
            </div>
        </div>
    `;
    
    paginationDiv.innerHTML = paginationHtml;
}

// 跳转到指定页面
function goToTeamReservationPage(page) {
    const searchTerm = document.getElementById('teamReservationSearch').value.trim();
    
    if (searchTerm) {
        searchTeamReservations(page);
    } else {
        loadTeamReservations(page);
    }
}

// 搜索团队预约
async function searchTeamReservations(page = 1) {
    const searchTerm = document.getElementById('teamReservationSearch').value.trim();
    const status = document.getElementById('teamStatusFilter').value;
    
    // 重置到第一页
    currentTeamReservationPage = page;
    
    if (!searchTerm && !status) {
        loadTeamReservations(page);
        return;
    }
    
    try {
        const tableBody = document.getElementById('teamReservationsTable');
        if (!tableBody) {
            console.error('无法找到团队预约表格元素');
            return;
        }
        tableBody.innerHTML = '<tr><td colspan="12" class="loading">搜索中...</td></tr>';
        
        let apiUrl = `team_reservations.php?action=list&page=${page}&limit=${teamReservationPageSize}`;
        if (searchTerm) {
            apiUrl += `&keyword=${encodeURIComponent(searchTerm)}`;
        }
        if (status) {
            apiUrl += `&status=${encodeURIComponent(status)}`;
        }
        
        const response = await apiRequest(apiUrl);
        if (response.code === 200) {
            const data = response.data;
            const teamReservations = data.list || [];
            
            // 更新分页信息
            if (data.pagination) {
                totalTeamReservationPages = data.pagination.pages || 0;
                totalTeamReservationCount = data.pagination.total || 0;
                updateTeamReservationPagination(data.pagination);
            }
            
            displayTeamReservations(teamReservations);
            
            // 初始化权限控制
            initializePermissions();
        } else {
            showAlert('teamReservationsAlert', response.message || '搜索失败');
            const tableBody = document.getElementById('teamReservationsTable');
            if (tableBody) {
                tableBody.innerHTML = '<tr><td colspan="12" class="loading">搜索失败</td></tr>';
            }
        }
    } catch (error) {
        console.error('搜索团队预约失败:', error);
        showAlert('teamReservationsAlert', '搜索失败：' + error.message);
        const tableBody = document.getElementById('teamReservationsTable');
        if (tableBody) {
            tableBody.innerHTML = '<tr><td colspan="12" class="loading">搜索失败</td></tr>';
        }
    }
}

// 按状态筛选团队预约
function filterTeamReservationsByStatus() {
    // 重置到第一页进行筛选
    searchTeamReservations(1);
}





// 更新团队预约状态
async function updateTeamReservationStatus(id, newStatus) {
    const statusText = getStatusText(newStatus);
    let adminNotes = '';
    
    if (newStatus === 'rejected') {
        adminNotes = prompt('请输入拒绝原因：');
        if (adminNotes === null) {
            return; // 用户取消了操作
        }
    }
    
    if (!confirm(`确定要将团队预约状态更改为"${statusText}"吗？`)) {
        return;
    }
    
    try {
        const response = await apiRequest('team_reservations.php?action=update_status', {
            method: 'PUT',
            body: JSON.stringify({
                id: id,
                status: newStatus,
                admin_notes: adminNotes
            })
        });
        
        if (response.code === 200) {
            showAlert('teamReservationsAlert', `团队预约状态更新为"${statusText}"成功！`, 'success');
            // 保持当前页面和搜索条件
            const searchTerm = document.getElementById('teamReservationSearch').value.trim();
            const status = document.getElementById('teamStatusFilter').value;
            if (searchTerm || status) {
                searchTeamReservations(currentTeamReservationPage);
            } else {
                loadTeamReservations(currentTeamReservationPage);
            }
        } else {
            alert(response.message || '状态更新失败');
        }
    } catch (error) {
        console.error('更新团队预约状态失败:', error);
        alert('更新团队预约状态失败：' + error.message);
    }
}

// 查看团队预约详情
async function viewTeamReservationDetail(id) {
    try {
        const response = await apiRequest(`team_reservations.php?action=detail&id=${id}`);
        if (response.code === 200) {
            const reservation = response.data;
            
            const detailHtml = `
                <h3>${reservation.team_name}</h3>
                <div style="margin-bottom: 20px; padding: 15px; background: #f8f9fa; border-radius: 5px;">
                    <p><strong>预约状态:</strong> <span style="color: ${reservation.status === 'approved' ? '#28a745' : reservation.status === 'rejected' ? '#dc3545' : '#6c757d'};\">${getStatusText(reservation.status)}</span></p>
                    <p><strong>创建时间:</strong> ${reservation.created_at}</p>
                    ${reservation.approved_at ? `<p><strong>审核时间:</strong> ${reservation.approved_at}</p>` : ''}
                    ${reservation.approved_by_name ? `<p><strong>审核人:</strong> ${reservation.approved_by_name}</p>` : ''}
                </div>
                
                <h4>基本信息</h4>
                <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9; width: 120px;"><strong>团队名称:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${reservation.team_name}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>参观者身份:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${reservation.visitor_identity}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>联系人:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${reservation.contact_name}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>联系单位:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${reservation.contact_unit}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>联系电话:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${reservation.contact_phone}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>预约日期:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${reservation.reservation_date}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>预约时间:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${reservation.reservation_time}${reservation.end_time ? ' - ' + reservation.end_time : ''}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>参观人数:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;"><span style="background: #17a2b8; color: white; padding: 4px 8px; border-radius: 12px;">${reservation.visitor_count}人</span></td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9;"><strong>是否需要讲解:</strong></td>
                        <td style="padding: 8px; border: 1px solid #ddd;">${reservation.need_guide == 1 ? '需要讲解' : '不需要讲解'}</td>
                    </tr>
                </table>
                
                ${reservation.visitor_info ? `
                <h4>参观者详细信息</h4>
                <div style="padding: 15px; background: #f8f9fa; border-radius: 5px; margin-bottom: 20px;">
                    ${reservation.visitor_info}
                </div>
                ` : ''}
                
                ${reservation.admin_notes ? `
                <h4>管理员备注</h4>
                <div style="padding: 15px; background: #f8d7da; border-radius: 5px; margin-bottom: 20px;">
                    ${reservation.admin_notes}
                </div>
                ` : ''}
            `;
            
            // 打开新窗口显示详情
            const detailWindow = window.open('', '_blank', 'width=900,height=800,scrollbars=yes');
            detailWindow.document.write(`
                <html>
                <head>
                    <title>团队预约详情 - ${reservation.team_name}</title>
                    <meta charset="UTF-8">
                    <style>
                        body { 
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
                            padding: 20px; 
                            background: #f8f9fa;
                            line-height: 1.6;
                        }
                        .container {
                            max-width: 900px;
                            margin: 0 auto;
                            background: white;
                            padding: 30px;
                            border-radius: 8px;
                            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                        }
                        h3 { color: #2c3e50; margin-top: 0; }
                        h4 { color: #34495e; margin: 20px 0 10px 0; border-bottom: 2px solid #3498db; padding-bottom: 5px; }
                        table { font-size: 14px; }
                        @media print {
                            body { background: white; }
                            .container { box-shadow: none; }
                        }
                    </style>
                </head>
                <body>
                    <div class="container">
                        ${detailHtml}
                        <div style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; color: #666;">
                            <small>博物馆团队预约管理系统</small>
                        </div>
                    </div>
                </body>
                </html>
            `);
        } else {
            alert(response.message || '获取团队预约详情失败');
        }
    } catch (error) {
        console.error('获取团队预约详情失败:', error);
        alert('获取团队预约详情失败：' + error.message);
    }
}

// ================================
// 订阅消息模板管理功能
// ================================

// 加载订阅消息模板列表
async function loadSubscribeTemplates() {
    try {
        const response = await apiRequest('subscribe_template_management.php?action=list', 'GET');
        const tableBody = document.getElementById('subscribeTemplatesTable');
        
        if (response.data && response.data.length > 0) {
            tableBody.innerHTML = response.data.map(template => `
                <tr>
                    <td>${template.id}</td>
                    <td><code>${template.template_key}</code></td>
                    <td>${template.template_name}</td>
                    <td>${getTemplateTypeLabel(template.template_type)}</td>
                    <td><code style="font-size: 0.8em;">${template.template_id}</code></td>
                    <td title="${template.description}">${truncateText(template.description, 20)}</td>
                    <td><span class="status-badge ${template.is_active ? 'status-open' : 'status-closed'}">${template.is_active ? '启用' : '禁用'}</span></td>
                    <td>${formatDateTime(template.updated_at)}</td>
                    <td>
                        <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="editSubscribeTemplate(${template.id})">编辑</button>
                        <button class="btn btn-primary" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="testTemplate('${template.template_id}')">测试</button>
                        <button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" onclick="deleteSubscribeTemplate(${template.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        } else {
            tableBody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #999;">暂无模板配置</td></tr>';
        }
        
        // 加载模板选项到筛选器
        loadTemplateOptions();
        
    } catch (error) {
        console.error('加载订阅模板失败:', error);
        showAlert('subscribeTemplatesAlert', '加载失败：' + error.message, 'error');
    }
}

// 获取模板类型标签
function getTemplateTypeLabel(type) {
    const typeMap = {
        'reservation': '预约相关',
        'team_reservation': '团队预约',
        'volunteer': '志愿者',
        'activity': '活动相关'
    };
    return typeMap[type] || type;
}

// 截断文本
function truncateText(text, maxLength) {
    if (!text) return '';
    return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
}

// 添加订阅消息模板
function addSubscribeTemplate() {
    // 清空表单
    document.getElementById('templateKey').value = '';
    document.getElementById('templateName').value = '';
    document.getElementById('templateType').value = '';
    document.getElementById('wechatTemplateId').value = '';
    document.getElementById('templateDescription').value = '';
    document.getElementById('dataFormat').value = '';
    document.getElementById('templateStatus').value = '1';
    
    // 显示模态框
    document.getElementById('addSubscribeTemplateModal').style.display = 'block';
}

// 保存订阅消息模板
async function saveSubscribeTemplate() {
    const templateKey = document.getElementById('templateKey').value.trim();
    const templateName = document.getElementById('templateName').value.trim();
    const templateType = document.getElementById('templateType').value;
    const wechatTemplateId = document.getElementById('wechatTemplateId').value.trim();
    const templateDescription = document.getElementById('templateDescription').value.trim();
    const dataFormat = document.getElementById('dataFormat').value.trim();
    const templateStatus = document.getElementById('templateStatus').value;
    
    // 表单验证
    if (!templateKey || !templateName || !templateType || !wechatTemplateId || !dataFormat) {
        alert('请填写所有必填字段');
        return;
    }
    
    // 验证模板标识格式
    if (!/^[A-Z][A-Z0-9_]*$/.test(templateKey)) {
        alert('模板标识必须为大写字母开头，只能包含大写字母、数字和下划线');
        return;
    }
    
    // 验证JSON格式
    try {
        JSON.parse(dataFormat);
    } catch (e) {
        alert('数据格式不是有效的JSON');
        return;
    }
    
    try {
        const response = await apiRequest('subscribe_template_management.php?action=add', 'POST', {
            template_key: templateKey,
            template_id: wechatTemplateId,
            template_name: templateName,
            template_type: templateType,
            description: templateDescription,
            data_format: dataFormat,
            is_active: parseInt(templateStatus)
        });
        
        showAlert('subscribeTemplatesAlert', response.message, 'success');
        closeModal('addSubscribeTemplateModal');
        loadSubscribeTemplates();
        
    } catch (error) {
        console.error('保存模板失败:', error);
        alert('保存失败：' + error.message);
    }
}

// 编辑订阅消息模板
async function editSubscribeTemplate(id) {
    try {
        const response = await apiRequest(`subscribe_template_management.php?action=detail&id=${id}`, 'GET');
        const template = response.data;
        
        // 填充编辑表单
        document.getElementById('editTemplateKey').value = template.template_key;
        document.getElementById('editTemplateName').value = template.template_name;
        document.getElementById('editTemplateType').value = template.template_type;
        document.getElementById('editWechatTemplateId').value = template.template_id;
        document.getElementById('editTemplateDescription').value = template.description || '';
        document.getElementById('editDataFormat').value = template.data_format;
        document.getElementById('editTemplateStatus').value = template.is_active;
        
        // 存储当前编辑的模板ID
        document.getElementById('editSubscribeTemplateModal').setAttribute('data-template-id', id);
        
        // 显示模态框
        document.getElementById('editSubscribeTemplateModal').style.display = 'block';
        
    } catch (error) {
        console.error('获取模板详情失败:', error);
        alert('获取模板详情失败：' + error.message);
    }
}

// 更新订阅消息模板
async function updateSubscribeTemplate() {
    const templateId = document.getElementById('editSubscribeTemplateModal').getAttribute('data-template-id');
    const templateName = document.getElementById('editTemplateName').value.trim();
    const templateType = document.getElementById('editTemplateType').value;
    const wechatTemplateId = document.getElementById('editWechatTemplateId').value.trim();
    const templateDescription = document.getElementById('editTemplateDescription').value.trim();
    const dataFormat = document.getElementById('editDataFormat').value.trim();
    const templateStatus = document.getElementById('editTemplateStatus').value;
    
    // 表单验证
    if (!templateName || !templateType || !wechatTemplateId || !dataFormat) {
        alert('请填写所有必填字段');
        return;
    }
    
    // 验证JSON格式
    try {
        JSON.parse(dataFormat);
    } catch (e) {
        alert('数据格式不是有效的JSON');
        return;
    }
    
    try {
        const response = await apiRequest('subscribe_template_management.php?action=update', 'PUT', {
            id: templateId,
            template_id: wechatTemplateId,
            template_name: templateName,
            template_type: templateType,
            description: templateDescription,
            data_format: dataFormat,
            is_active: parseInt(templateStatus)
        });
        
        showAlert('subscribeTemplatesAlert', response.message, 'success');
        closeModal('editSubscribeTemplateModal');
        loadSubscribeTemplates();
        
    } catch (error) {
        console.error('更新模板失败:', error);
        alert('更新失败：' + error.message);
    }
}

// 删除订阅消息模板
async function deleteSubscribeTemplate(id) {
    if (!confirm('确定要删除这个模板吗？删除后不可恢复。')) {
        return;
    }
    
    try {
        const response = await apiRequest(`subscribe_template_management.php?action=delete&id=${id}`, 'DELETE');
        showAlert('subscribeTemplatesAlert', response.message, 'success');
        loadSubscribeTemplates();
        
    } catch (error) {
        console.error('删除模板失败:', error);
        alert('删除失败：' + error.message);
    }
}

// 测试微信配置
async function testWeChatConfig() {
    try {
        const response = await apiRequest('subscribe_template_management.php?action=test_config', 'GET');
        
        alert(`配置测试成功！\n\nAppID: ${response.data.appid}\nAccess Token: ${response.data.token_prefix}\n有效期: ${response.data.expires_in}秒`);
        
    } catch (error) {
        console.error('测试微信配置失败:', error);
        alert('测试失败：' + error.message + '\n\n请检查：\n1. 微信AppID和Secret是否正确\n2. 网络连接是否正常\n3. 微信接口是否可访问');
    }
}

// 测试模板消息
function testTemplate(templateId) {
    // 加载模板选项
    loadTemplateOptionsForTest();
    
    // 设置默认选中的模板
    document.getElementById('testTemplateId').value = templateId;
    loadTemplateDataFormat();
    
    // 显示测试模态框
    document.getElementById('testMessageModal').style.display = 'block';
}

// 加载模板选项（用于测试）
async function loadTemplateOptionsForTest() {
    try {
        const response = await apiRequest('subscribe_template_management.php?action=list&status=1', 'GET');
        const select = document.getElementById('testTemplateId');
        
        select.innerHTML = '<option value="">请选择模板</option>';
        if (response.data) {
            response.data.forEach(template => {
                select.innerHTML += `<option value="${template.template_id}" data-format='${template.data_format}'>${template.template_name} (${template.template_key})</option>`;
            });
        }
    } catch (error) {
        console.error('加载模板选项失败:', error);
    }
}

// 加载模板数据格式
function loadTemplateDataFormat() {
    const select = document.getElementById('testTemplateId');
    const selectedOption = select.options[select.selectedIndex];
    
    if (selectedOption && selectedOption.dataset.format) {
        const format = JSON.parse(selectedOption.dataset.format);
        const exampleData = {};
        
        // 生成示例数据
        Object.keys(format).forEach(key => {
            const description = format[key];
            switch (key) {
                case 'thing1':
                case 'thing2':
                case 'thing3':
                case 'thing4':
                    exampleData[key] = { value: description.includes('名称') ? '测试项目' : '测试内容' };
                    break;
                case 'date2':
                case 'date3':
                    exampleData[key] = { value: new Date().toISOString().split('T')[0] };
                    break;
                case 'time3':
                    exampleData[key] = { value: new Date().toTimeString().split(' ')[0].substring(0, 5) };
                    break;
                case 'phrase2':
                    exampleData[key] = { value: '审核通过' };
                    break;
                default:
                    exampleData[key] = { value: '测试数据' };
            }
        });
        
        document.getElementById('testMessageData').value = JSON.stringify(exampleData, null, 2);
    } else {
        document.getElementById('testMessageData').value = '';
    }
}

// 发送测试消息
async function sendTestMessage() {
    const templateId = document.getElementById('testTemplateId').value;
    const openId = document.getElementById('testOpenId').value.trim();
    const messageData = document.getElementById('testMessageData').value.trim();
    const miniProgramState = document.getElementById('testMiniProgramState').value;
    
    if (!templateId || !openId || !messageData) {
        alert('请填写所有必填字段');
        return;
    }
    
    // 验证消息数据JSON格式
    let parsedData;
    try {
        parsedData = JSON.parse(messageData);
    } catch (e) {
        alert('消息数据不是有效的JSON格式');
        return;
    }
    
    try {
        const response = await apiRequest('subscribe_message.php?action=send', 'POST', {
            openid: openId,
            template_id: templateId,
            data: parsedData,
            miniprogram_state: miniProgramState
        });
        
        alert('测试消息发送成功！');
        closeModal('testMessageModal');
        
    } catch (error) {
        console.error('发送测试消息失败:', error);
        alert('发送失败：' + error.message + '\n\n可能原因：\n1. 用户未订阅该模板\n2. OpenID无效\n3. 模板数据格式不正确');
    }
}

// 加载消息发送日志
async function loadMessageLogs() {
    const startDate = document.getElementById('logStartDate').value;
    const endDate = document.getElementById('logEndDate').value;
    const templateFilter = document.getElementById('logTemplateFilter').value;
    
    if (!startDate && !endDate) {
        alert('请至少选择一个日期范围');
        return;
    }
    
    try {
        let url = 'subscribe_template_management.php?action=logs';
        if (startDate) url += `&start_date=${startDate}`;
        if (endDate) url += `&end_date=${endDate}`;
        if (templateFilter) url += `&template_id=${templateFilter}`;
        
        const response = await apiRequest(url, 'GET');
        const tableBody = document.getElementById('messageLogsTable');
        
        if (response.data && response.data.length > 0) {
            tableBody.innerHTML = response.data.map(log => {
                const result = JSON.parse(log.send_result || '{}');
                const isSuccess = result.errcode === 0;
                
                return `
                    <tr>
                        <td>${log.id}</td>
                        <td><code style="font-size: 0.8em;">${log.openid.substring(0, 8)}...</code></td>
                        <td><span title="${log.template_name || ''}">${log.template_id}</span></td>
                        <td><span class="status-badge ${isSuccess ? 'status-open' : 'status-closed'}">${isSuccess ? '成功' : '失败'}</span></td>
                        <td>${formatDateTime(log.created_at)}</td>
                        <td>
                            <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" onclick="showMessageLogDetail(${log.id})">详情</button>
                        </td>
                    </tr>
                `;
            }).join('');
        } else {
            tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #999;">没有找到相关日志</td></tr>';
        }
        
    } catch (error) {
        console.error('加载消息日志失败:', error);
        showAlert('subscribeTemplatesAlert', '加载日志失败：' + error.message, 'error');
    }
}

// 显示消息日志详情
async function showMessageLogDetail(id) {
    try {
        const response = await apiRequest(`subscribe_template_management.php?action=log_detail&id=${id}`, 'GET');
        const log = response.data;
        const result = JSON.parse(log.send_result || '{}');
        const messageData = JSON.parse(log.message_data || '{}');
        
        // 填充详情信息
        document.getElementById('logDetailBasic').innerHTML = `
            <div><strong>日志ID:</strong> ${log.id}</div>
            <div><strong>用户OpenID:</strong> <code>${log.openid}</code></div>
            <div><strong>模板ID:</strong> <code>${log.template_id}</code></div>
            <div><strong>发送时间:</strong> ${formatDateTime(log.created_at)}</div>
            <div><strong>发送状态:</strong> <span class="status-badge ${result.errcode === 0 ? 'status-open' : 'status-closed'}">${result.errcode === 0 ? '成功' : '失败'}</span></div>
        `;
        
        document.getElementById('logDetailData').value = JSON.stringify(messageData, null, 2);
        document.getElementById('logDetailResult').value = JSON.stringify(result, null, 2);
        
        // 显示详情模态框
        document.getElementById('messageLogDetailModal').style.display = 'block';
        
    } catch (error) {
        console.error('获取日志详情失败:', error);
        alert('获取详情失败：' + error.message);
    }
}

// 清理旧日志
async function clearOldLogs() {
    if (!confirm('确定要删除30天前的消息日志吗？此操作不可恢复。')) {
        return;
    }
    
    try {
        const response = await apiRequest('subscribe_template_management.php?action=clear_logs&days=30', 'DELETE');
        alert(response.message);
        
        // 重新加载日志
        loadMessageLogs();
        
    } catch (error) {
        console.error('清理日志失败:', error);
        alert('清理失败：' + error.message);
    }
}

// 筛选模板（按类型）
function filterTemplatesByType() {
    const type = document.getElementById('templateTypeFilter').value;
    const status = document.getElementById('templateStatusFilter').value;
    loadFilteredTemplates(type, status);
}

// 筛选模板（按状态）
function filterTemplatesByStatus() {
    const type = document.getElementById('templateTypeFilter').value;
    const status = document.getElementById('templateStatusFilter').value;
    loadFilteredTemplates(type, status);
}

// 加载筛选后的模板
async function loadFilteredTemplates(type = '', status = '') {
    try {
        let url = 'subscribe_template_management.php?action=list';
        if (type) url += `&type=${type}`;
        if (status !== '') url += `&status=${status}`;
        
        const response = await apiRequest(url, 'GET');
        const tableBody = document.getElementById('subscribeTemplatesTable');
        
        if (response.data && response.data.length > 0) {
            tableBody.innerHTML = response.data.map(template => `
                <tr>
                    <td>${template.id}</td>
                    <td><code>${template.template_key}</code></td>
                    <td>${template.template_name}</td>
                    <td>${getTemplateTypeLabel(template.template_type)}</td>
                    <td><code style="font-size: 0.8em;">${template.template_id}</code></td>
                    <td title="${template.description}">${truncateText(template.description, 20)}</td>
                    <td><span class="status-badge ${template.is_active ? 'status-open' : 'status-closed'}">${template.is_active ? '启用' : '禁用'}</span></td>
                    <td>${formatDateTime(template.updated_at)}</td>
                    <td>
                        <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="editSubscribeTemplate(${template.id})">编辑</button>
                        <button class="btn btn-primary" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="testTemplate('${template.template_id}')">测试</button>
                        <button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" onclick="deleteSubscribeTemplate(${template.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        } else {
            tableBody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #999;">暂无匹配的模板</td></tr>';
        }
    } catch (error) {
        console.error('加载模板失败:', error);
        showAlert('subscribeTemplatesAlert', '加载失败：' + error.message, 'error');
    }
}

// 加载模板选项到日志筛选器
async function loadTemplateOptions() {
    try {
        const response = await apiRequest('subscribe_template_management.php?action=list', 'GET');
        const select = document.getElementById('logTemplateFilter');
        
        select.innerHTML = '<option value="">全部模板</option>';
        if (response.data) {
            response.data.forEach(template => {
                select.innerHTML += `<option value="${template.template_id}">${template.template_name} (${template.template_key})</option>`;
            });
        }
    } catch (error) {
        console.error('加载模板选项失败:', error);
    }
}

// 格式化日期时间
function formatDateTime(dateStr) {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// ================== 内容管理功能 ==================

// 全局变量 - 富文本编辑器实例
let chapterBriefEditor = null;
let addChapterEditor = null;
let editChapterBriefEditor = null;
let editChapterContentEditor = null;
let viewChapterEditor = null;

let exhibitBriefEditor = null;
let exhibitContentEditor = null;
let editExhibitBriefEditor = null;
let editExhibitContentEditor = null;

let itemContentEditor = null;
let editItemContentEditor = null;

// ================== 篇章管理功能 ==================

// 加载篇章列表
async function loadChapters() {
    console.log('🔄 开始加载篇章数据...');
    
    try {
        // 检查表格元素是否存在
        const tableBody = document.getElementById('chaptersTable');
        if (!tableBody) {
            console.error('❌ chaptersTable 元素不存在');
            alert('页面元素错误：找不到篇章表格');
            return;
        }

        console.log('📡 正在请求API: content_management.php?action=chapters');
        
        // 直接使用fetch，避免apiRequest可能的问题
        const response = await fetch(API_BASE + 'content_management.php?action=chapters', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            }
        });

        console.log('📡 API响应状态:', response.status, response.statusText);

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();
        console.log('📦 API返回数据:', data);

        if (data.success || data.code === 200) {
            const chapters = data.data || data;
            console.log('✅ 篇章数据解析成功，共', chapters.length, '条记录');

            if (chapters && chapters.length > 0) {
                tableBody.innerHTML = chapters.map(chapter => `
                    <tr>
                        <td>${chapter.id}</td>
                        <td><strong>${chapter.name}</strong></td>
                        <td>${chapter.english_name || '-'}</td>
                        <td>${chapter.sort}</td>
                        <td>${formatDateTime(chapter.created_at)}</td>
                        <td>${formatDateTime(chapter.updated_at)}</td>
                        <td>
                            <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="viewChapter(${chapter.id})">查看</button>
                            <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="editChapter(${chapter.id})">编辑</button>
                            <button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" onclick="deleteChapter(${chapter.id})">删除</button>
                        </td>
                    </tr>
                `).join('');
                console.log('✅ 表格更新完成');
            } else {
                tableBody.innerHTML = '<tr><td colspan="7">暂无数据</td></tr>';
                console.log('ℹ️ 无篇章数据');
            }
        } else {
            console.error('❌ API返回失败:', data.message || '未知错误');
            tableBody.innerHTML = '<tr><td colspan="7">数据加载失败</td></tr>';
            
            // 尝试备用API
            console.log('🔄 尝试备用API...');
            await loadChaptersBackup();
        }
    } catch (error) {
        console.error('❌ 加载篇章列表失败:', error);
        
        // 显示详细错误信息
        const tableBody = document.getElementById('chaptersTable');
        if (tableBody) {
            tableBody.innerHTML = `<tr><td colspan="7">加载失败: ${error.message}</td></tr>`;
        }
        
        // 尝试备用API
        console.log('🔄 尝试备用API...');
        await loadChaptersBackup();
        
        showAlert('chaptersAlert', '加载失败：' + error.message, 'error');
    }
}

// 备用加载函数
async function loadChaptersBackup() {
    try {
        console.log('📡 使用备用API: content_direct.php?action=chapters');
        
        const response = await fetch(API_BASE + 'content_direct.php?action=chapters', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            }
        });

        if (!response.ok) {
            throw new Error(`备用API失败: ${response.status}`);
        }

        const data = await response.json();
        console.log('📦 备用API返回:', data);

        if (data.success && data.data) {
            const tableBody = document.getElementById('chaptersTable');
            if (tableBody) {
                tableBody.innerHTML = data.data.map(chapter => `
                    <tr>
                        <td>${chapter.id}</td>
                        <td><strong>${chapter.name}</strong></td>
                        <td>${chapter.english_name || '-'}</td>
                        <td>${chapter.sort}</td>
                        <td>${formatDateTime(chapter.created_at)}</td>
                        <td>${formatDateTime(chapter.updated_at)}</td>
                        <td>
                            <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="viewChapter(${chapter.id})">查看</button>
                            <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="editChapter(${chapter.id})">编辑</button>
                            <button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" onclick="deleteChapter(${chapter.id})">删除</button>
                        </td>
                    </tr>
                `).join('');
                console.log('✅ 备用API加载成功');
            }
        }
    } catch (backupError) {
        console.error('❌ 备用API也失败:', backupError);
    }
}

// 添加篇章
function addChapter() {
    // 为null则第一次进入，避免重复实例化编辑器报错
    if (addChapterEditor == null) {
        let { createEditor, createToolbar } = window.wangEditor
		//实例化编辑器
		addChapterEditor = createEditor({
			selector: '#addChapterEditor',
		})
		let toolbarConfig = {}
		//排除指定的菜单,排除图片上传和视频上传
		toolbarConfig.excludeKeys = ['group-image','group-video',]
		var toolbar = createToolbar({
			editor: addChapterEditor,
			selector: '#addChapterToolbar',
			config: toolbarConfig,
		})
    }

    // 清空表单
    document.getElementById('addChapterName').value = '';
    document.getElementById('addChapterSort').value = '';
    addChapterEditor.setHtml('');
    document.getElementById('addChapterModal').style.display = 'block';
}

// 保存篇章
// async function saveChapter() {
//     const name = document.getElementById('chapterName').value.trim();
//     const englishName = document.getElementById('chapterEnglishName').value.trim();
//     const brief = chapterBriefEditor.root.innerHTML;
//     const content = chapterContentEditor.root.innerHTML;
//     const sort = document.getElementById('chapterSort').value;
    
//     if (!name) {
//         alert('请填写篇章名称');
//         return;
//     }
    
//     if (!sort) {
//         alert('请填写排序');
//         return;
//     }
    
//     try {
//         const response = await apiRequest('content_management.php?action=add_chapter', 'POST', {
//             name,
//             english_name: englishName,
//             brief,
//             content,
//             sort: parseInt(sort)
//         });
        
//         showAlert('chaptersAlert', response.message, response.success ? 'success' : 'error');
//         if (response.success) {
//             closeModal('addChapterModal');
//             loadChapters();
//         }
//     } catch (error) {
//         console.error('保存篇章失败:', error);
//         alert('保存失败: ' + error.message);
//     }
// }
// 保存篇章（支持图片上传）
async function saveChapter() {
    const name = document.getElementById('addChapterName').value.trim();
    const sort = document.getElementById('addChapterSort').value;
    
    if (!name) {
        alert('请填写篇章名称');
        return;
    }
    
    if (!sort || sort < 1) {
        alert('请填写有效的排序值');
        return;
    }

    try {
        // 创建FormData对象用于文件上传
        const formData = new FormData();
        // 添加基本数据
        formData.append('name', name);
        formData.append('sort', parseInt(sort));
        // 添加富文本内容
        if (typeof addChapterEditor !== 'undefined' && addChapterEditor) {
            formData.append('content', addChapterEditor.getHtml());
        } else {
            formData.append('content', '');
        }
        
        // 添加选择的图片
        selectedChapterImages.forEach((file, index) => {
            formData.append('images[]', file);
        });
        // 显示加载状态
        const saveButton = event.target;
        const originalText = saveButton.textContent;
        saveButton.textContent = '保存中...';
        saveButton.disabled = true;

        // const response = await apiRequest('content_management.php?action=add_chapter', 'POST', formData);

        // 发送请求
        const response = await fetch(API_BASE + 'content_management.php?action=add_chapter', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${getToken()}`
            },
            body: formData
        });

        console.log(response);

        // clearChapterImages(); // 清空选择的图片
        // loadChapters(); // 重新加载列表
        // 恢复按钮状态
        saveButton.textContent = originalText;
        saveButton.disabled = false;
        
        // showAlert('chaptersAlert', response.message, response.success ? 'success' : 'error');
        // if (response.success) {
        //     closeModal('addChapterModal');
        //     loadChapters();
        // }
    } catch (error) {
        console.error('保存篇章失败:', error);
        alert('保存失败: ' + error.message);
    }

}

// 编辑篇章
async function editChapter(id) {
    try {
        const response = await apiRequest(`content_management.php?action=chapter&id=${id}`, 'GET');
        
        if (response.success && response.data) {
            const chapter = response.data;
            
            document.getElementById('editChapterName').value = chapter.name;
            document.getElementById('editChapterEnglishName').value = chapter.english_name || '';
            document.getElementById('editChapterSort').value = chapter.sort;
            
            // 初始化编辑器
            if (!editChapterBriefEditor) {
                editChapterBriefEditor = new Quill('#editChapterBriefEditor', { theme: 'snow' });
            }
            if (!editChapterContentEditor) {
                editChapterContentEditor = new Quill('#editChapterContentEditor', { theme: 'snow' });
            }
            
            editChapterBriefEditor.root.innerHTML = chapter.brief || '';
            editChapterContentEditor.root.innerHTML = chapter.content || '';
            
            document.getElementById('editChapterModal').setAttribute('data-chapter-id', id);
            document.getElementById('editChapterModal').style.display = 'block';
        }
    } catch (error) {
        console.error('获取篇章信息失败:', error);
        alert('获取信息失败: ' + error.message);
    }
}

// 更新篇章
async function updateChapter() {
    const chapterId = document.getElementById('editChapterModal').getAttribute('data-chapter-id');
    const name = document.getElementById('editChapterName').value.trim();
    const englishName = document.getElementById('editChapterEnglishName').value.trim();
    const brief = editChapterBriefEditor.root.innerHTML;
    const content = editChapterContentEditor.root.innerHTML;
    const sort = document.getElementById('editChapterSort').value;
    
    if (!name) {
        alert('请填写篇章名称');
        return;
    }
    
    try {
        const response = await apiRequest('content_management.php?action=update_chapter', 'POST', {
            id: chapterId,
            name,
            english_name: englishName,
            brief,
            content,
            sort: parseInt(sort)
        });
        
        showAlert('chaptersAlert', response.message, response.success ? 'success' : 'error');
        if (response.success) {
            closeModal('editChapterModal');
            loadChapters();
        }
    } catch (error) {
        console.error('更新篇章失败:', error);
        alert('更新失败: ' + error.message);
    }
}

// 删除篇章
async function deleteChapter(id) {
    if (!confirm('确定要删除这个篇章吗？删除后其下的所有展项和展品也会被删除！')) {
        return;
    }
    
    try {
        const response = await apiRequest(`content_management.php?action=delete_chapter&id=${id}`, 'DELETE');
        showAlert('chaptersAlert', response.message, response.success ? 'success' : 'error');
        if (response.success) {
            loadChapters();
        }
    } catch (error) {
        console.error('删除篇章失败:', error);
        alert('删除失败: ' + error.message);
    }
}

// 查看篇章详情
async function viewChapter(id) {
    try {
		// 为null则第一次进入，避免重复实例化编辑器报错
        if (viewChapterEditor == null) {
            // 实例化编辑器
            let { createEditor, createToolbar } = window.wangEditor
            let editorConfig = {
                readOnly: true,
            }
            //实例化编辑器
            viewChapterEditor = createEditor({
                selector: '#viewChapterEditor',
                config: editorConfig,
            })
        }
        // 把原来的内容清空
        document.getElementById('viewChapterName').value = '';
        document.getElementById('viewChapterSort').value = '';
        document.getElementById('viewChapterImage').innerHTML = '';
        viewChapterEditor.setHtml('');

        let response = await apiRequest(`content_management.php?action=chapter&id=${id}`, 'GET');
        if (response.code === 200 && response.data) {
            document.getElementById('viewChapterName').value = response.data.name;
            document.getElementById('viewChapterSort').value = response.data.sort;
            let srcStr = '';
            for (let i = 0; i < response.data.images.length; i++) {
                srcStr += `<img src="${response.data.images[i]}" style="height: 200px; margin-bottom: 10px;">`;
            }
            document.getElementById('viewChapterImage').innerHTML = srcStr;
            //将内容填充到编辑器中
            viewChapterEditor.setHtml(response.data.content);
        }
        document.getElementById('viewChapterModal').style.display = 'block';
    } catch (error) {
        console.error('获取篇章详情失败:', error);
        alert('获取详情失败: ' + error.message);
    }
}

// ================== 展项管理功能 ==================

// 加载展项列表
async function loadExhibits() {
    console.log('🔄 开始加载展项数据...');
    
    try {
        const tableBody = document.getElementById('exhibitsTable');
        if (!tableBody) {
            console.error('❌ exhibitsTable 元素不存在');
            return;
        }

        const response = await fetch(API_BASE + 'content_management.php?action=exhibits', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        });

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();
        console.log('📦 展项API返回:', data);

        if (data.success || data.code === 200) {
            const exhibits = data.data || data;
            
            if (exhibits && exhibits.length > 0) {
                tableBody.innerHTML = exhibits.map(exhibit => `
                    <tr>
                        <td>${exhibit.id}</td>
                        <td>${exhibit.chapter_name || '未知篇章'}</td>
                        <td><strong>${exhibit.name}</strong></td>
                        <td>${exhibit.english_name || '-'}</td>
                        <td>${exhibit.sort}</td>
                        <td>${formatDateTime(exhibit.created_at)}</td>
                        <td>
                            <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="viewExhibit(${exhibit.id})">查看</button>
                            <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="editExhibit(${exhibit.id})">编辑</button>
                            <button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" onclick="deleteExhibit(${exhibit.id})">删除</button>
                        </td>
                    </tr>
                `).join('');
                console.log('✅ 展项表格更新完成');
            } else {
                tableBody.innerHTML = '<tr><td colspan="7">暂无数据</td></tr>';
            }
        } else {
            console.error('❌ 展项API返回失败:', data.message);
            tableBody.innerHTML = '<tr><td colspan="7">数据加载失败</td></tr>';
        }
    } catch (error) {
        console.error('❌ 加载展项失败:', error);
        const tableBody = document.getElementById('exhibitsTable');
        if (tableBody) {
            tableBody.innerHTML = `<tr><td colspan="7">加载失败: ${error.message}</td></tr>`;
        }
        showAlert('exhibitsAlert', '加载失败：' + error.message, 'error');
    }
}

// 加载篇章筛选选项
async function loadChapterFilterOptions() {
    try {
        const response = await apiRequest('content_management.php?action=chapters', 'GET');
        if (response.success && response.data) {
            const select = document.getElementById('chapterFilter');
            select.innerHTML = '<option value="">全部篇章</option>';
            response.data.forEach(chapter => {
                select.innerHTML += `<option value="${chapter.id}">${chapter.name}</option>`;
            });
        }
    } catch (error) {
        console.error('加载篇章选项失败:', error);
    }
}

// 按篇章筛选展项
function filterExhibitsByChapter() {
    const chapterId = document.getElementById('chapterFilter').value;
    if (chapterId) {
        loadExhibitsByChapter(chapterId);
    } else {
        loadExhibits();
    }
}

// 按篇章加载展项
async function loadExhibitsByChapter(chapterId) {
    try {
        const response = await apiRequest(`content_management.php?action=exhibits&chapter_id=${chapterId}`, 'GET');
        const tableBody = document.getElementById('exhibitsTable');
        
        if (response.success && response.data) {
            tableBody.innerHTML = response.data.map(exhibit => `
                <tr>
                    <td>${exhibit.id}</td>
                    <td>${exhibit.chapter_name || '未知篇章'}</td>
                    <td><strong>${exhibit.name}</strong></td>
                    <td>${exhibit.english_name || '-'}</td>
                    <td>${exhibit.sort}</td>
                    <td>${formatDateTime(exhibit.created_at)}</td>
                    <td>
                        <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="viewExhibit(${exhibit.id})">查看</button>
                        <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="editExhibit(${exhibit.id})">编辑</button>
                        <button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" onclick="deleteExhibit(${exhibit.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        } else {
            tableBody.innerHTML = '<tr><td colspan="7">暂无数据</td></tr>';
        }
    } catch (error) {
        console.error('加载展项失败:', error);
        showAlert('exhibitsAlert', '加载失败：' + error.message, 'error');
    }
}

// 添加展项
async function addExhibit() {
    // 清空表单
    document.getElementById('exhibitName').value = '';
    document.getElementById('exhibitEnglishName').value = '';
    document.getElementById('exhibitSort').value = '1';
    
    // 加载篇章选项
    await loadChapterOptions('exhibitChapter');
    
    // 初始化富文本编辑器
    if (!exhibitBriefEditor) {
        exhibitBriefEditor = new Quill('#exhibitBriefEditor', { theme: 'snow' });
    }
    if (!exhibitContentEditor) {
        exhibitContentEditor = new Quill('#exhibitContentEditor', { theme: 'snow' });
    }
    
    exhibitBriefEditor.root.innerHTML = '';
    exhibitContentEditor.root.innerHTML = '';
    
    document.getElementById('addExhibitModal').style.display = 'block';
}

// 保存展项
async function saveExhibit() {
    const chapterId = document.getElementById('exhibitChapter').value;
    const name = document.getElementById('exhibitName').value.trim();
    const englishName = document.getElementById('exhibitEnglishName').value.trim();
    const brief = exhibitBriefEditor.root.innerHTML;
    const content = exhibitContentEditor.root.innerHTML;
    const sort = document.getElementById('exhibitSort').value;
    
    if (!chapterId) {
        alert('请选择所属篇章');
        return;
    }
    
    if (!name) {
        alert('请填写展项名称');
        return;
    }
    
    try {
        const response = await apiRequest('content_management.php?action=add_exhibit', 'POST', {
            one_id: chapterId,
            name,
            english_name: englishName,
            brief,
            content,
            sort: parseInt(sort)
        });
        
        showAlert('exhibitsAlert', response.message, response.success ? 'success' : 'error');
        if (response.success) {
            closeModal('addExhibitModal');
            loadExhibits();
        }
    } catch (error) {
        console.error('保存展项失败:', error);
        alert('保存失败: ' + error.message);
    }
}

// 编辑展项
async function editExhibit(id) {
    try {
        const response = await apiRequest(`content_management.php?action=exhibit&id=${id}`, 'GET');
        
        if (response.success && response.data) {
            const exhibit = response.data;
            
            // 加载篇章选项
            await loadChapterOptions('editExhibitChapter');
            
            document.getElementById('editExhibitChapter').value = exhibit.one_id;
            document.getElementById('editExhibitName').value = exhibit.name;
            document.getElementById('editExhibitEnglishName').value = exhibit.english_name || '';
            document.getElementById('editExhibitSort').value = exhibit.sort;
            
            // 初始化编辑器
            if (!editExhibitBriefEditor) {
                editExhibitBriefEditor = new Quill('#editExhibitBriefEditor', { theme: 'snow' });
            }
            if (!editExhibitContentEditor) {
                editExhibitContentEditor = new Quill('#editExhibitContentEditor', { theme: 'snow' });
            }
            
            editExhibitBriefEditor.root.innerHTML = exhibit.brief || '';
            editExhibitContentEditor.root.innerHTML = exhibit.content || '';
            
            document.getElementById('editExhibitModal').setAttribute('data-exhibit-id', id);
            document.getElementById('editExhibitModal').style.display = 'block';
        }
    } catch (error) {
        console.error('获取展项信息失败:', error);
        alert('获取信息失败: ' + error.message);
    }
}

// 更新展项
async function updateExhibit() {
    const exhibitId = document.getElementById('editExhibitModal').getAttribute('data-exhibit-id');
    const chapterId = document.getElementById('editExhibitChapter').value;
    const name = document.getElementById('editExhibitName').value.trim();
    const englishName = document.getElementById('editExhibitEnglishName').value.trim();
    const brief = editExhibitBriefEditor.root.innerHTML;
    const content = editExhibitContentEditor.root.innerHTML;
    const sort = document.getElementById('editExhibitSort').value;
    
    if (!name) {
        alert('请填写展项名称');
        return;
    }
    
    try {
        const response = await apiRequest('content_management.php?action=update_exhibit', 'POST', {
            id: exhibitId,
            one_id: chapterId,
            name,
            english_name: englishName,
            brief,
            content,
            sort: parseInt(sort)
        });
        
        showAlert('exhibitsAlert', response.message, response.success ? 'success' : 'error');
        if (response.success) {
            closeModal('editExhibitModal');
            loadExhibits();
        }
    } catch (error) {
        console.error('更新展项失败:', error);
        alert('更新失败: ' + error.message);
    }
}

// 删除展项
async function deleteExhibit(id) {
    if (!confirm('确定要删除这个展项吗？删除后其下的所有展品也会被删除！')) {
        return;
    }
    
    try {
        const response = await apiRequest(`content_management.php?action=delete_exhibit&id=${id}`, 'DELETE');
        showAlert('exhibitsAlert', response.message, response.success ? 'success' : 'error');
        if (response.success) {
            loadExhibits();
        }
    } catch (error) {
        console.error('删除展项失败:', error);
        alert('删除失败: ' + error.message);
    }
}

// 查看展项详情
async function viewExhibit(id) {
    try {
        const response = await apiRequest(`content_management.php?action=exhibit&id=${id}`, 'GET');
        if (response.success && response.data) {
            const exhibit = response.data;
            alert(`展项详情：\n\n名称：${exhibit.name}\n英文名：${exhibit.english_name || '无'}\n所属篇章：${exhibit.chapter_name}\n排序：${exhibit.sort}\n创建时间：${exhibit.created_at}`);
        }
    } catch (error) {
        console.error('获取展项详情失败:', error);
        alert('获取详情失败: ' + error.message);
    }
}

// ================== 展品管理功能 ==================

// 加载展品列表
async function loadItems() {
    console.log('🔄 开始加载展品数据...');
    
    try {
        const tableBody = document.getElementById('itemsTable');
        if (!tableBody) {
            console.error('❌ itemsTable 元素不存在');
            return;
        }

        const response = await fetch(API_BASE + 'content_management.php?action=items', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        });

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();
        console.log('📦 展品API返回:', data);

        if (data.success || data.code === 200) {
            const items = data.data || data;
            
            if (items && items.length > 0) {
                tableBody.innerHTML = items.map(item => `
                    <tr>
                        <td>${item.id}</td>
                        <td>${item.chapter_name || '未知篇章'}</td>
                        <td>${item.exhibit_name || '未知展项'}</td>
                        <td><strong>${item.name}</strong></td>
                        <td>${item.sort}</td>
                        <td>${formatDateTime(item.created_at)}</td>
                        <td>
                            <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="viewItem(${item.id})">查看</button>
                            <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="editItem(${item.id})">编辑</button>
                            <button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" onclick="deleteItem(${item.id})">删除</button>
                        </td>
                    </tr>
                `).join('');
                console.log('✅ 展品表格更新完成');
            } else {
                tableBody.innerHTML = '<tr><td colspan="7">暂无数据</td></tr>';
            }
        } else {
            console.error('❌ 展品API返回失败:', data.message);
            tableBody.innerHTML = '<tr><td colspan="7">数据加载失败</td></tr>';
        }
    } catch (error) {
        console.error('❌ 加载展品失败:', error);
        const tableBody = document.getElementById('itemsTable');
        if (tableBody) {
            tableBody.innerHTML = `<tr><td colspan="7">加载失败: ${error.message}</td></tr>`;
        }
        showAlert('itemsAlert', '加载失败：' + error.message, 'error');
    }
}

// 加载展品筛选选项
async function loadItemFilterOptions() {
    try {
        // 加载篇章选项
        const chaptersResponse = await apiRequest('content_management.php?action=chapters', 'GET');
        if (chaptersResponse.success && chaptersResponse.data) {
            const chapterSelect = document.getElementById('itemChapterFilter');
            chapterSelect.innerHTML = '<option value="">选择篇章</option>';
            chaptersResponse.data.forEach(chapter => {
                chapterSelect.innerHTML += `<option value="${chapter.id}">${chapter.name}</option>`;
            });
        }
    } catch (error) {
        console.error('加载筛选选项失败:', error);
    }
}

// 更新展品的展项筛选选项
async function updateItemExhibitFilter() {
    const chapterId = document.getElementById('itemChapterFilter').value;
    const exhibitSelect = document.getElementById('itemExhibitFilter');
    
    if (!chapterId) {
        exhibitSelect.innerHTML = '<option value="">选择展项</option>';
        return;
    }
    
    try {
        const response = await apiRequest(`content_management.php?action=exhibits&chapter_id=${chapterId}`, 'GET');
        if (response.success && response.data) {
            exhibitSelect.innerHTML = '<option value="">选择展项</option>';
            response.data.forEach(exhibit => {
                exhibitSelect.innerHTML += `<option value="${exhibit.id}">${exhibit.name}</option>`;
            });
        }
    } catch (error) {
        console.error('加载展项选项失败:', error);
    }
}

// 按展项筛选展品
function filterItemsByExhibit() {
    const chapterId = document.getElementById('itemChapterFilter').value;
    const exhibitId = document.getElementById('itemExhibitFilter').value;
    
    if (exhibitId) {
        loadItemsByExhibit(chapterId, exhibitId);
    } else if (chapterId) {
        loadItemsByChapter(chapterId);
    } else {
        loadItems();
    }
}

// 按展项加载展品
async function loadItemsByExhibit(chapterId, exhibitId) {
    try {
        const response = await apiRequest(`content_management.php?action=items&chapter_id=${chapterId}&exhibit_id=${exhibitId}`, 'GET');
        const tableBody = document.getElementById('itemsTable');
        
        if (response.success && response.data) {
            tableBody.innerHTML = response.data.map(item => `
                <tr>
                    <td>${item.id}</td>
                    <td>${item.chapter_name || '未知篇章'}</td>
                    <td>${item.exhibit_name || '未知展项'}</td>
                    <td><strong>${item.name}</strong></td>
                    <td>${item.sort}</td>
                    <td>${formatDateTime(item.created_at)}</td>
                    <td>
                        <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="viewItem(${item.id})">查看</button>
                        <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="editItem(${item.id})">编辑</button>
                        <button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" onclick="deleteItem(${item.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        } else {
            tableBody.innerHTML = '<tr><td colspan="7">暂无数据</td></tr>';
        }
    } catch (error) {
        console.error('加载展品失败:', error);
        showAlert('itemsAlert', '加载失败：' + error.message, 'error');
    }
}

// 按篇章加载展品
async function loadItemsByChapter(chapterId) {
    try {
        const response = await apiRequest(`content_management.php?action=items&chapter_id=${chapterId}`, 'GET');
        const tableBody = document.getElementById('itemsTable');
        
        if (response.success && response.data) {
            tableBody.innerHTML = response.data.map(item => `
                <tr>
                    <td>${item.id}</td>
                    <td>${item.chapter_name || '未知篇章'}</td>
                    <td>${item.exhibit_name || '未知展项'}</td>
                    <td><strong>${item.name}</strong></td>
                    <td>${item.sort}</td>
                    <td>${formatDateTime(item.created_at)}</td>
                    <td>
                        <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="viewItem(${item.id})">查看</button>
                        <button class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" onclick="editItem(${item.id})">编辑</button>
                        <button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" onclick="deleteItem(${item.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        } else {
            tableBody.innerHTML = '<tr><td colspan="7">暂无数据</td></tr>';
        }
    } catch (error) {
        console.error('加载展品失败:', error);
        showAlert('itemsAlert', '加载失败：' + error.message, 'error');
    }
}

// 添加展品
async function addItem() {
    // 清空表单
    document.getElementById('itemName').value = '';
    document.getElementById('itemSort').value = '1';
    
    // 加载篇章选项
    await loadChapterOptions('itemChapter');
    
    // 初始化富文本编辑器
    if (!itemContentEditor) {
        itemContentEditor = new Quill('#itemContentEditor', { theme: 'snow' });
    }
    
    itemContentEditor.root.innerHTML = '';
    
    document.getElementById('addItemModal').style.display = 'block';
}

// 保存展品
async function saveItem() {
    const chapterId = document.getElementById('itemChapter').value;
    const exhibitId = document.getElementById('itemExhibit').value;
    const name = document.getElementById('itemName').value.trim();
    const content = itemContentEditor.root.innerHTML;
    const sort = document.getElementById('itemSort').value;
    
    if (!chapterId) {
        alert('请选择所属篇章');
        return;
    }
    
    if (!exhibitId) {
        alert('请选择所属展项');
        return;
    }
    
    if (!name) {
        alert('请填写展品名称');
        return;
    }
    
    try {
        const response = await apiRequest('content_management.php?action=add_item', 'POST', {
            one_id: chapterId,
            two_id: exhibitId,
            name,
            content,
            sort: parseInt(sort)
        });
        
        showAlert('itemsAlert', response.message, response.success ? 'success' : 'error');
        if (response.success) {
            closeModal('addItemModal');
            loadItems();
        }
    } catch (error) {
        console.error('保存展品失败:', error);
        alert('保存失败: ' + error.message);
    }
}

// 编辑展品
async function editItem(id) {
    try {
        const response = await apiRequest(`content_management.php?action=item&id=${id}`, 'GET');
        
        if (response.success && response.data) {
            const item = response.data;
            
            // 加载篇章选项
            await loadChapterOptions('editItemChapter');
            
            document.getElementById('editItemChapter').value = item.one_id;
            document.getElementById('editItemName').value = item.name;
            document.getElementById('editItemSort').value = item.sort;
            
            // 更新展项选项
            await updateEditItemExhibits();
            document.getElementById('editItemExhibit').value = item.two_id;
            
            // 初始化编辑器
            if (!editItemContentEditor) {
                editItemContentEditor = new Quill('#editItemContentEditor', { theme: 'snow' });
            }
            
            editItemContentEditor.root.innerHTML = item.content || '';
            
            document.getElementById('editItemModal').setAttribute('data-item-id', id);
            document.getElementById('editItemModal').style.display = 'block';
        }
    } catch (error) {
        console.error('获取展品信息失败:', error);
        alert('获取信息失败: ' + error.message);
    }
}

// 更新展品
async function updateItem() {
    const itemId = document.getElementById('editItemModal').getAttribute('data-item-id');
    const chapterId = document.getElementById('editItemChapter').value;
    const exhibitId = document.getElementById('editItemExhibit').value;
    const name = document.getElementById('editItemName').value.trim();
    const content = editItemContentEditor.root.innerHTML;
    const sort = document.getElementById('editItemSort').value;
    
    if (!name) {
        alert('请填写展品名称');
        return;
    }
    
    try {
        const response = await apiRequest('content_management.php?action=update_item', 'POST', {
            id: itemId,
            one_id: chapterId,
            two_id: exhibitId,
            name,
            content,
            sort: parseInt(sort)
        });
        
        showAlert('itemsAlert', response.message, response.success ? 'success' : 'error');
        if (response.success) {
            closeModal('editItemModal');
            loadItems();
        }
    } catch (error) {
        console.error('更新展品失败:', error);
        alert('更新失败: ' + error.message);
    }
}

// 删除展品
async function deleteItem(id) {
    if (!confirm('确定要删除这个展品吗？')) {
        return;
    }
    
    try {
        const response = await apiRequest(`content_management.php?action=delete_item&id=${id}`, 'DELETE');
        showAlert('itemsAlert', response.message, response.success ? 'success' : 'error');
        if (response.success) {
            loadItems();
        }
    } catch (error) {
        console.error('删除展品失败:', error);
        alert('删除失败: ' + error.message);
    }
}

// 查看展品详情
async function viewItem(id) {
    try {
        const response = await apiRequest(`content_management.php?action=item&id=${id}`, 'GET');
        if (response.success && response.data) {
            const item = response.data;
            alert(`展品详情：\n\n名称：${item.name}\n所属篇章：${item.chapter_name}\n所属展项：${item.exhibit_name}\n排序：${item.sort}\n创建时间：${item.created_at}`);
        }
    } catch (error) {
        console.error('获取展品详情失败:', error);
        alert('获取详情失败: ' + error.message);
    }
}

// 更新展项选项 (添加展品时)
async function updateItemExhibits() {
    const chapterId = document.getElementById('itemChapter').value;
    const exhibitSelect = document.getElementById('itemExhibit');
    
    if (!chapterId) {
        exhibitSelect.innerHTML = '<option value="">请先选择篇章</option>';
        return;
    }
    
    try {
        const response = await apiRequest(`content_management.php?action=exhibits&chapter_id=${chapterId}`, 'GET');
        if (response.success && response.data) {
            exhibitSelect.innerHTML = '<option value="">请选择展项</option>';
            response.data.forEach(exhibit => {
                exhibitSelect.innerHTML += `<option value="${exhibit.id}">${exhibit.name}</option>`;
            });
        }
    } catch (error) {
        console.error('加载展项选项失败:', error);
    }
}

// 更新展项选项 (编辑展品时)
async function updateEditItemExhibits() {
    const chapterId = document.getElementById('editItemChapter').value;
    const exhibitSelect = document.getElementById('editItemExhibit');
    
    if (!chapterId) {
        exhibitSelect.innerHTML = '<option value="">请先选择篇章</option>';
        return;
    }
    
    try {
        const response = await apiRequest(`content_management.php?action=exhibits&chapter_id=${chapterId}`, 'GET');
        if (response.success && response.data) {
            exhibitSelect.innerHTML = '<option value="">请选择展项</option>';
            response.data.forEach(exhibit => {
                exhibitSelect.innerHTML += `<option value="${exhibit.id}">${exhibit.name}</option>`;
            });
        }
    } catch (error) {
        console.error('加载展项选项失败:', error);
    }
}

// ================== 多媒体管理功能 ==================

// 加载多媒体文件列表
async function loadMedia() {
    try {
        const response = await apiRequest('content_management.php?action=media', 'GET');
        const tableBody = document.getElementById('mediaTable');
        
        if (response.success && response.data) {
            tableBody.innerHTML = response.data.map(media => `
                <tr>
                    <td>${media.id}</td>
                    <td>${media.content_name || '未知内容'}</td>
                    <td>${getLevelLabel(media.level)}</td>
                    <td>${getTypeLabel(media.type)}</td>
                    <td>${getMediaPreview(media.url, media.type)}</td>
                    <td>${formatDateTime(media.created_at)}</td>
                    <td>
                        <button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" onclick="deleteMedia(${media.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        } else {
            tableBody.innerHTML = '<tr><td colspan="7">暂无数据</td></tr>';
        }
    } catch (error) {
        console.error('加载多媒体列表失败:', error);
        showAlert('mediaAlert', '加载失败：' + error.message, 'error');
    }
}

// ================== 辅助函数 ==================

// 加载篇章选项到指定下拉框
async function loadChapterOptions(selectId) {
    try {
        const response = await apiRequest('content_management.php?action=chapters', 'GET');
        if (response.success && response.data) {
            const select = document.getElementById(selectId);
            select.innerHTML = '<option value="">请选择篇章</option>';
            response.data.forEach(chapter => {
                select.innerHTML += `<option value="${chapter.id}">${chapter.name}</option>`;
            });
        }
    } catch (error) {
        console.error('加载篇章选项失败:', error);
    }
}

// 获取级别标签
function getLevelLabel(level) {
    const labels = { 1: '篇章', 2: '展项', 3: '展品' };
    return labels[level] || '未知';
}

// 获取类型标签
function getTypeLabel(type) {
    const labels = { 1: '图片', 2: '音频', 3: '视频' };
    return labels[type] || '未知';
}

// 获取媒体预览
function getMediaPreview(url, type) {
    const fullUrl = `../uploads/${url}`;
    switch (type) {
        case 1:
            return `<img src="${fullUrl}" style="max-width: 100px; max-height: 60px;" alt="图片预览">`;
        case 2:
            return `<audio controls style="width: 200px;"><source src="${fullUrl}"></audio>`;
        case 3:
            return `<video controls style="width: 200px; height: 100px;"><source src="${fullUrl}"></video>`;
        default:
            return '无法预览';
    }
}

// 添加多媒体
async function addMedia() {
    // 清空表单
    document.getElementById('mediaLevel').value = '';
    document.getElementById('mediaTarget').value = '';
    document.getElementById('mediaType').value = '';
    document.getElementById('mediaFile').value = '';
    
    // 清空目标选项
    document.getElementById('mediaTarget').innerHTML = '<option value="">请先选择级别</option>';
    
    document.getElementById('addMediaModal').style.display = 'block';
}

// 更新多媒体关联目标
async function updateMediaTargets() {
    const level = document.getElementById('mediaLevel').value;
    const targetSelect = document.getElementById('mediaTarget');
    
    if (!level) {
        targetSelect.innerHTML = '<option value="">请先选择级别</option>';
        return;
    }
    
    try {
        const response = await apiRequest(`content_management.php?action=targets&level=${level}`, 'GET');
        if (response.success && response.data) {
            targetSelect.innerHTML = '<option value="">请选择关联内容</option>';
            response.data.forEach(target => {
                targetSelect.innerHTML += `<option value="${target.id}">${target.name}</option>`;
            });
        }
    } catch (error) {
        console.error('加载关联目标失败:', error);
        targetSelect.innerHTML = '<option value="">加载失败</option>';
    }
}

// 保存多媒体文件
async function saveMedia() {
    const level = document.getElementById('mediaLevel').value;
    const exhibitId = document.getElementById('mediaTarget').value;
    const type = document.getElementById('mediaType').value;
    const fileInput = document.getElementById('mediaFile');
    
    if (!level) {
        alert('请选择关联级别');
        return;
    }
    
    if (!exhibitId) {
        alert('请选择关联内容');
        return;
    }
    
    if (!type) {
        alert('请选择文件类型');
        return;
    }
    
    if (!fileInput.files[0]) {
        alert('请选择要上传的文件');
        return;
    }
    
    // 这里应该实现文件上传功能
    // 由于涉及文件上传，需要使用FormData和专门的上传API
    alert('多媒体上传功能需要单独的文件上传接口，当前版本暂未实现。');
    closeModal('addMediaModal');
}

// 删除多媒体文件
async function deleteMedia(id) {
    if (!confirm('确定要删除这个多媒体文件吗？')) {
        return;
    }
    
    try {
        const response = await apiRequest(`content_management.php?action=delete_media&id=${id}`, 'DELETE');
        showAlert('mediaAlert', response.message, response.success ? 'success' : 'error');
        if (response.success) {
            loadMedia();
        }
    } catch (error) {
        console.error('删除多媒体文件失败:', error);
        alert('删除失败: ' + error.message);
    }
}

// 按级别筛选多媒体
function filterMediaByLevel() {
    const level = document.getElementById('mediaLevelFilter').value;
    const type = document.getElementById('mediaTypeFilter').value;
    loadMediaWithFilters(level, type);
}

// 按类型筛选多媒体
function filterMediaByType() {
    const level = document.getElementById('mediaLevelFilter').value;
    const type = document.getElementById('mediaTypeFilter').value;
    loadMediaWithFilters(level, type);
}

// 带筛选条件加载多媒体
async function loadMediaWithFilters(level = '', type = '') {
    try {
        let url = 'content_management.php?action=media';
        if (level) url += `&level=${level}`;
        if (type) url += `&type=${type}`;
        
        const response = await apiRequest(url, 'GET');
        const tableBody = document.getElementById('mediaTable');
        
        if (response.success && response.data) {
            tableBody.innerHTML = response.data.map(media => `
                <tr>
                    <td>${media.id}</td>
                    <td>${media.content_name || '未知内容'}</td>
                    <td>${getLevelLabel(media.level)}</td>
                    <td>${getTypeLabel(media.type)}</td>
                    <td>${getMediaPreview(media.url, media.type)}</td>
                    <td>${formatDateTime(media.created_at)}</td>
                    <td>
                        <button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" onclick="deleteMedia(${media.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        } else {
            tableBody.innerHTML = '<tr><td colspan="7">暂无数据</td></tr>';
        }
    } catch (error) {
        console.error('加载多媒体列表失败:', error);
        showAlert('mediaAlert', '加载失败：' + error.message, 'error');
    }
}

// 关闭模态框
function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

// ===== 轮播图管理相关函数 =====

// 全局变量
let currentCarouselId = null;

// 加载轮播图统计信息
async function loadCarouselStats() {
    try {
        const response = await apiRequest('carousel_management_simple.php?action=stats', 'GET');
        if (response.success) {
            const stats = response.data;
            document.getElementById('carouselTotalCount').textContent = stats.total || 0;
            document.getElementById('carouselActiveCount').textContent = stats.active || 0;
            document.getElementById('carouselTotalViews').textContent = stats.total_views || 0;
            document.getElementById('carouselTotalClicks').textContent = stats.total_clicks || 0;
        }
    } catch (error) {
        console.error('加载轮播图统计失败:', error);
    }
}

// 加载轮播图列表
async function loadCarousels() {
    try {
        const search = document.getElementById('carouselSearch').value;
        const status = document.getElementById('carouselStatusFilter').value;
        
        let url = 'carousel_management_simple.php';
        const params = new URLSearchParams();
        if (search) params.append('search', search);
        if (status) params.append('status', status);
        if (params.toString()) url += '?' + params.toString();
        
        const response = await apiRequest(url, 'GET');
        const tableBody = document.getElementById('carouselsTable');
        
        if (response.success && response.data.list) {
            tableBody.innerHTML = response.data.list.map(carousel => `
                <tr>
                    <td>${carousel.id}</td>
                    <td>
                        <img src="${carousel.image_url}" alt="${carousel.title}" 
                             style="width: 80px; height: 40px; object-fit: cover; border-radius: 4px;"
                             onerror="this.src=''">
                    </td>
                    <td>${carousel.title}</td>
                    <td>${getLinkTypeText(carousel.link_type)}</td>
                    <td>${carousel.sort}</td>
                    <td>
                        <span class="status-badge ${carousel.status === 'active' ? 'status-open' : 'status-closed'}">
                            ${carousel.status === 'active' ? '启用' : '禁用'}
                        </span>
                    </td>
                    <td>${carousel.view_count} / ${carousel.click_count}</td>
                    <td>${formatDateTime(carousel.created_at)}</td>
                    <td>
                        <button class="btn btn-primary" style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" 
                                onclick="editCarousel(${carousel.id})">编辑</button>
                        <button class="btn ${carousel.status === 'active' ? 'btn-danger' : 'btn-success'}" 
                                style="padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.25rem;" 
                                onclick="toggleCarouselStatus(${carousel.id}, '${carousel.status}')">
                            ${carousel.status === 'active' ? '禁用' : '启用'}
                        </button>
                        <button class="btn btn-danger" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" 
                                onclick="deleteCarousel(${carousel.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        } else {
            tableBody.innerHTML = '<tr><td colspan="7">暂无轮播图数据</td></tr>';
        }
        
        // 同时加载统计信息
        loadCarouselStats();
        
    } catch (error) {
        console.error('加载轮播图列表失败:', error);
        showAlert('carouselsAlert', '加载失败：' + error.message, 'error');
    }
}

// 获取链接类型文本
function getLinkTypeText(type) {
    const types = {
        'none': '无链接',
        'url': '外部链接',
        'page': '小程序页面',
        'miniprogram': '小程序跳转'
    };
    return types[type] || type;
}

// 搜索轮播图
function searchCarousels() {
    loadCarousels();
}

// 按状态筛选轮播图
function filterCarouselsByStatus() {
    loadCarousels();
}

// 添加轮播图
function addCarousel() {
    currentCarouselId = null;
    document.getElementById('carouselTitle').value = '';
    document.getElementById('carouselImageUrl').value = '';
    document.getElementById('carouselLinkType').value = 'none';
    document.getElementById('carouselLinkValue').value = '';
    document.getElementById('carouselSort').value = '0';
    document.getElementById('carouselStatus').value = 'active';
    document.getElementById('addCarouselModal').style.display = 'block';
}

// 编辑轮播图
async function editCarousel(id) {
    currentCarouselId = id;
    
    try {
        const response = await apiRequest(`carousel_management_simple.php?id=${id}`, 'GET');
        if (response.success) {
            const carousel = response.data;
            document.getElementById('editCarouselTitle').value = carousel.title;
            document.getElementById('editCarouselImageUrl').value = carousel.image_url;
            document.getElementById('editCarouselLinkType').value = carousel.link_type;
            document.getElementById('editCarouselLinkValue').value = carousel.link_value || '';
            document.getElementById('editCarouselSort').value = carousel.sort;
            document.getElementById('editCarouselStatus').value = carousel.status;
            document.getElementById('editCarouselModal').style.display = 'block';
        } else {
            alert('加载轮播图数据失败: ' + response.message);
        }
    } catch (error) {
        console.error('加载轮播图数据失败:', error);
        alert('加载失败: ' + error.message);
    }
}

// 保存轮播图（新增）
async function saveCarousel() {
    const title = document.getElementById('carouselTitle').value.trim();
    const imageUrl = document.getElementById('carouselImageUrl').value.trim();
    const linkType = document.getElementById('carouselLinkType').value;
    const linkValue = document.getElementById('carouselLinkValue').value.trim();
    const sort = parseInt(document.getElementById('carouselSort').value) || 0;
    const status = document.getElementById('carouselStatus').value;
    
    if (!title) {
        alert('请输入轮播图标题');
        return;
    }
    
    if (!imageUrl) {
        alert('请输入图片URL');
        return;
    }
    
    const data = {
        title,
        image_url: imageUrl,
        link_type: linkType,
        link_value: linkValue,
        sort,
        status
    };
    
    try {
        const response = await apiRequest('carousel_management_simple.php', {
            method: 'POST',
            body: JSON.stringify(data)
        });
        showAlert('carouselsAlert', response.message, response.success ? 'success' : 'error');
        
        if (response.success) {
            closeModal('addCarouselModal');
            loadCarousels();
        }
    } catch (error) {
        console.error('保存轮播图失败:', error);
        alert('保存失败: ' + error.message);
    }
}

// 更新轮播图
async function updateCarousel() {
    if (!currentCarouselId) {
        alert('当前编辑ID丢失');
        return;
    }
    
    const title = document.getElementById('editCarouselTitle').value.trim();
    const imageUrl = document.getElementById('editCarouselImageUrl').value.trim();
    const linkType = document.getElementById('editCarouselLinkType').value;
    const linkValue = document.getElementById('editCarouselLinkValue').value.trim();
    const sort = parseInt(document.getElementById('editCarouselSort').value) || 0;
    const status = document.getElementById('editCarouselStatus').value;
    
    if (!title) {
        alert('请输入轮播图标题');
        return;
    }
    
    if (!imageUrl) {
        alert('请输入图片URL');
        return;
    }
    
    const data = {
        title,
        image_url: imageUrl,
        link_type: linkType,
        link_value: linkValue,
        sort,
        status
    };
    
    try {
        const response = await apiRequest(`carousel_management_simple.php?id=${currentCarouselId}`, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
        showAlert('carouselsAlert', response.message, response.success ? 'success' : 'error');
        
        if (response.success) {
            closeModal('editCarouselModal');
            loadCarousels();
        }
    } catch (error) {
        console.error('更新轮播图失败:', error);
        alert('更新失败: ' + error.message);
    }
}

// 切换轮播图状态
async function toggleCarouselStatus(id, currentStatus) {
    const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    const action = newStatus === 'active' ? '启用' : '禁用';
    
    if (!confirm(`确定要${action}这个轮播图吗？`)) {
        return;
    }
    
    try {
        const response = await apiRequest(`carousel_management_simple.php?id=${id}`, {
            method: 'PUT',
            body: JSON.stringify({ status: newStatus })
        });
        showAlert('carouselsAlert', response.message, response.success ? 'success' : 'error');
        
        if (response.success) {
            loadCarousels();
        }
    } catch (error) {
        console.error('切换状态失败:', error);
        alert('操作失败: ' + error.message);
    }
}

// 删除轮播图
async function deleteCarousel(id) {
    if (!confirm('确定要删除这个轮播图吗？删除后无法恢复！')) {
        return;
    }
    
    try {
        const response = await apiRequest(`carousel_management_simple.php?id=${id}`, {
            method: 'DELETE'
        });
        showAlert('carouselsAlert', response.message, response.success ? 'success' : 'error');
        
        if (response.success) {
            loadCarousels();
        }
    } catch (error) {
        console.error('删除轮播图失败:', error);
        alert('删除失败: ' + error.message);
    }
}

// ======================== 团队预约审核功能 ========================

let currentReviewReservationId = null;

// 打开团队预约审核模态框
async function reviewTeamReservation(id) {
    currentReviewReservationId = id;
    
    try {
        const response = await apiRequest(`team_reservations.php?action=detail&id=${id}`);
        if (response.code === 200) {
            const reservation = response.data;
            populateReviewModal(reservation);
            document.getElementById('teamReservationReviewModal').style.display = 'block';
        } else {
            alert('获取预约详情失败: ' + response.message);
        }
    } catch (error) {
        console.error('获取预约详情失败:', error);
        alert('获取预约详情失败: ' + error.message);
    }
}

// 填充审核模态框数据
function populateReviewModal(reservation) {
    // 基本信息
    const basicInfoHtml = `
        <div class="info-item">
            <div class="info-label">预约编号:</div>
            <div class="info-value"><strong>#${reservation.id}</strong></div>
        </div>
        <div class="info-item">
            <div class="info-label">团队名称:</div>
            <div class="info-value"><strong>${reservation.team_name}</strong></div>
        </div>
        <div class="info-item">
            <div class="info-label">预约日期:</div>
            <div class="info-value">
                <i class="fas fa-calendar-alt" style="color: #3498db; margin-right: 5px;"></i>
                ${reservation.reservation_date}
            </div>
        </div>
        <div class="info-item">
            <div class="info-label">预约时间:</div>
            <div class="info-value">
                <i class="fas fa-clock" style="color: #e74c3c; margin-right: 5px;"></i>
                ${reservation.reservation_time}${reservation.end_time ? ' - ' + reservation.end_time : ''}
            </div>
        </div>
        <div class="info-item">
            <div class="info-label">参观人数:</div>
            <div class="info-value">
                <span style="background: #3498db; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px;">
                    <i class="fas fa-users" style="margin-right: 3px;"></i>
                    ${reservation.visitor_count} 人
                </span>
            </div>
        </div>
        <div class="info-item">
            <div class="info-label">需要讲解:</div>
            <div class="info-value">
                <span style="background: ${reservation.need_guide == 1 ? '#27ae60' : '#95a5a6'}; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px;">
                    <i class="fas ${reservation.need_guide == 1 ? 'fa-check' : 'fa-times'}" style="margin-right: 3px;"></i>
                    ${reservation.need_guide == 1 ? '需要讲解' : '不需要讲解'}
                </span>
            </div>
        </div>
        <div class="info-item">
            <div class="info-label">申请时间:</div>
            <div class="info-value">
                <i class="fas fa-clock" style="color: #95a5a6; margin-right: 5px;"></i>
                ${new Date(reservation.created_at).toLocaleString('zh-CN')}
            </div>
        </div>
    `;

    // 联系人信息
    const contactInfoHtml = `
        <div class="info-item">
            <div class="info-label">联系人:</div>
            <div class="info-value"><strong>${reservation.contact_name}</strong></div>
        </div>
        <div class="info-item">
            <div class="info-label">所在单位:</div>
            <div class="info-value">${reservation.contact_unit || '-'}</div>
        </div>
        <div class="info-item">
            <div class="info-label">联系电话:</div>
            <div class="info-value">
                <a href="tel:${reservation.contact_phone}" style="color: #3498db; text-decoration: none;">
                    <i class="fas fa-phone" style="margin-right: 5px;"></i>
                    ${reservation.contact_phone}
                </a>
            </div>
        </div>
        <div class="info-item">
            <div class="info-label">参观者身份:</div>
            <div class="info-value">
                <span style="background: #f39c12; color: white; padding: 3px 10px; border-radius: 15px; font-size: 12px;">
                    ${reservation.visitor_identity}
                </span>
            </div>
        </div>
        <div class="info-item">
            <div class="info-label">当前状态:</div>
            <div class="info-value">
                ${getStatusBadge(reservation.status)}
            </div>
        </div>
    `;

    // 团队详细信息
    const teamDetailsHtml = `
        <div style="background: white; padding: 15px; border-radius: 8px; border: 1px solid #dee2e6;">
            <div style="margin-bottom: 10px;">
                <strong style="color: #2c3e50;">
                    <i class="fas fa-info-circle" style="color: #3498db; margin-right: 5px;"></i>
                    团队详细说明:
                </strong>
            </div>
            <div style="line-height: 1.8; color: #495057; font-size: 14px;">
                ${reservation.visitor_info ? reservation.visitor_info.replace(/\n/g, '<br>') : '暂无详细信息'}
            </div>
        </div>
        ${reservation.admin_notes ? `
        <div style="background: #fff3cd; padding: 15px; border-radius: 8px; border: 1px solid #ffeaa7; margin-top: 15px;">
            <div style="margin-bottom: 10px;">
                <strong style="color: #856404;">
                    <i class="fas fa-sticky-note" style="color: #f39c12; margin-right: 5px;"></i>
                    管理员备注:
                </strong>
            </div>
            <div style="line-height: 1.8; color: #856404; font-size: 14px;">
                ${reservation.admin_notes.replace(/\n/g, '<br>')}
            </div>
        </div>
        ` : ''}
    `;

    // 填充数据
    document.getElementById('reviewBasicInfo').innerHTML = basicInfoHtml;
    document.getElementById('reviewContactInfo').innerHTML = contactInfoHtml;
    document.getElementById('reviewTeamDetails').innerHTML = teamDetailsHtml;

    // 重置表单
    document.querySelectorAll('input[name="reviewDecision"]').forEach(radio => {
        radio.checked = false;
    });
    document.getElementById('reviewNotes').value = '';
}

// 获取状态徽章
function getStatusBadge(status) {
    const statusConfig = {
        'pending': { color: '#f39c12', text: '待审核', icon: 'fa-clock' },
        'approved': { color: '#27ae60', text: '已批准', icon: 'fa-check-circle' },
        'rejected': { color: '#e74c3c', text: '已拒绝', icon: 'fa-times-circle' },
        'cancelled': { color: '#95a5a6', text: '已取消', icon: 'fa-ban' },
        'completed': { color: '#3498db', text: '已完成', icon: 'fa-flag-checkered' }
    };

    const config = statusConfig[status] || { color: '#95a5a6', text: status, icon: 'fa-question-circle' };
    
    return `
        <span class="status-badge-large" style="background: ${config.color}; color: white;">
            <i class="fas ${config.icon}" style="margin-right: 5px;"></i>
            ${config.text}
        </span>
    `;
}

// 提交审核结果
async function submitTeamReservationReview() {
    if (!currentReviewReservationId) {
        alert('审核ID丢失，请重新打开审核页面');
        return;
    }

    const selectedDecision = document.querySelector('input[name="reviewDecision"]:checked');
    if (!selectedDecision) {
        alert('请选择审核结果');
        return;
    }

    const decision = selectedDecision.value;
    const notes = document.getElementById('reviewNotes').value.trim();

    // 如果是拒绝，必须填写拒绝原因
    if (decision === 'rejected' && !notes) {
        alert('拒绝预约时必须填写拒绝原因');
        return;
    }

    const decisionText = decision === 'approved' ? '批准' : '拒绝';
    
    if (!confirm(`确定要${decisionText}这个团队预约吗？`)) {
        return;
    }

    try {
        const response = await apiRequest('team_reservations.php?action=update_status', {
            method: 'PUT',
            body: JSON.stringify({
                id: currentReviewReservationId,
                status: decision,
                admin_notes: notes
            })
        });

        if (response.code === 200) {
            showAlert('teamReservationsAlert', `团队预约${decisionText}成功！`, 'success');
            closeModal('teamReservationReviewModal');
            
            // 刷新列表，保持当前页面和搜索状态
            const searchTerm = document.getElementById('teamReservationSearch').value.trim();
            const status = document.getElementById('teamStatusFilter').value;
            if (searchTerm || status) {
                searchTeamReservations(currentTeamReservationPage);
            } else {
                loadTeamReservations(currentTeamReservationPage);
            }
        } else {
            alert(response.message || '审核失败');
        }
    } catch (error) {
        console.error('提交审核失败:', error);
        alert('提交审核失败: ' + error.message);
    }
}

// ================================
// 常用观众管理功能
// ================================

// 加载常用观众列表
async function loadVisitorList() {
    try {
        const response = await apiRequest('admin/visitor_management.php?action=list');
        if (response.code === 200) {
            const visitors = response.data.list || response.data; // 处理两种可能的数据结构
            displayVisitorList(visitors);
            updateVisitorStatistics(visitors);
        } else {
            document.getElementById('visitorsTable').innerHTML = '<tr><td colspan="7" class="loading">加载失败: ' + (response.message || '未知错误') + '</td></tr>';
        }
    } catch (error) {
        console.error('加载常用观众失败:', error);
        document.getElementById('visitorsTable').innerHTML = '<tr><td colspan="7" class="loading">加载失败</td></tr>';
        showAlert('visitorsAlert', '加载常用观众失败：' + error.message);
    }
}

// 显示常用观众列表
function displayVisitorList(visitors) {
    const tbody = document.getElementById('visitorsTable');
    
    if (!visitors || !Array.isArray(visitors) || visitors.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="loading">暂无常用观众数据</td></tr>';
        return;
    }
    
    tbody.innerHTML = visitors.map(visitor => {
        const createTime = visitor.created_at ? new Date(visitor.created_at).toLocaleDateString('zh-CN') : '-';
        const userName = visitor.user_nickname || visitor.user_real_name || '-';
        
        // 证件类型中文映射
        const idTypeMap = {
            'id_card': '身份证',
            'passport': '护照',
            'military_id': '军官证',
            'other': '其他',
            '身份证': '身份证',
            '护照': '护照', 
            '军官证': '军官证',
            '其他': '其他',
            'ID_CARD': '身份证',
            'PASSPORT': '护照',
            'MILITARY_ID': '军官证',
            'OTHER': '其他',
            '1': '身份证',  // 可能的数字编码
            '2': '护照',
            '3': '军官证',
            '4': '其他'
        };
        const idTypeDisplay = idTypeMap[visitor.id_type] || visitor.id_type || '-';
        
        return `
            <tr>
                <td>${visitor.id}</td>
                <td>${visitor.name || '-'}</td>
                <td>${idTypeDisplay}</td>
                <td>${visitor.id_number || '-'}</td>
                <td>${visitor.phone || '-'}</td>
                <td>${userName}</td>
                <td>${createTime}</td>
            </tr>
        `;
    }).join('');
    
    // 初始化权限控制
    initializePermissions();
}

// 更新常用观众统计数据
function updateVisitorStatistics(visitors) {
    if (!visitors || !Array.isArray(visitors) || visitors.length === 0) {
        document.getElementById('visitorTotalCount').textContent = '0';
        document.getElementById('visitorUniqueUsers').textContent = '0';
        document.getElementById('visitorIdCardCount').textContent = '0';
        document.getElementById('visitorTodayCount').textContent = '0';
        return;
    }
    
    const totalCount = visitors.length;
    const uniqueUsers = new Set(visitors.filter(v => v.user_id).map(v => v.user_id)).size;
    const idCardCount = visitors.filter(v => v.id_type === '身份证').length;
    
    // 计算今日新增
    const today = new Date().toDateString();
    const todayCount = visitors.filter(v => {
        const visitorDate = new Date(v.created_at).toDateString();
        return visitorDate === today;
    }).length;
    
    document.getElementById('visitorTotalCount').textContent = totalCount;
    document.getElementById('visitorUniqueUsers').textContent = uniqueUsers;
    document.getElementById('visitorIdCardCount').textContent = idCardCount;
    document.getElementById('visitorTodayCount').textContent = todayCount;
}

// 搜索常用观众
async function searchVisitors() {
    const searchTerm = document.getElementById('visitorSearch').value.trim();
    const idType = document.getElementById('visitorIdTypeFilter').value;
    const userId = document.getElementById('visitorUserIdFilter').value;
    
    // 如果所有条件都为空，加载全部数据
    if (!searchTerm && !idType && !userId) {
        loadVisitorList();
        return;
    }
    
    try {
        document.getElementById('visitorsTable').innerHTML = '<tr><td colspan="7" class="loading">搜索中...</td></tr>';
        
        // 构建查询参数
        const params = new URLSearchParams();
        params.append('action', 'search');
        
        if (searchTerm) params.append('search', searchTerm);
        if (idType) params.append('id_type', idType);
        if (userId) params.append('user_id', userId);
        
        const response = await apiRequest(`admin/visitor_management.php?${params.toString()}`);
        if (response.code === 200) {
            const visitors = response.data.list || response.data; // 处理两种可能的数据结构
            displayVisitorList(visitors);
            updateVisitorStatistics(visitors);
        } else {
            showAlert('visitorsAlert', response.message || '搜索失败');
        }
    } catch (error) {
        console.error('搜索常用观众失败:', error);
        showAlert('visitorsAlert', '搜索失败：' + error.message);
        document.getElementById('visitorsTable').innerHTML = '<tr><td colspan="9" class="loading">搜索失败</td></tr>';
    }
}

// 编辑观众信息
async function editVisitor(visitorId) {
    try {
        const response = await apiRequest(`admin/visitor_management.php?action=detail&id=${visitorId}`);
        if (response.code === 200) {
            const visitor = response.data;
            showEditVisitorModal(visitor);
        } else {
            alert(response.message || '获取观众信息失败');
        }
    } catch (error) {
        console.error('获取观众信息失败:', error);
        alert('获取观众信息失败：' + error.message);
    }
}

// 显示编辑观众模态框
function showEditVisitorModal(visitor) {
    document.getElementById('editVisitorName').value = visitor.name || '';
    document.getElementById('editVisitorIdType').value = visitor.id_type || '';
    document.getElementById('editVisitorIdNumber').value = visitor.id_number || '';
    document.getElementById('editVisitorPhone').value = visitor.phone || '';
    
    // 保存当前编辑的观众ID
    document.getElementById('editVisitorModal').dataset.visitorId = visitor.id;
    
    // 显示模态框
    document.getElementById('editVisitorModal').style.display = 'block';
}

// 确认编辑观众信息
async function confirmEditVisitor() {
    const visitorId = document.getElementById('editVisitorModal').dataset.visitorId;
    const name = document.getElementById('editVisitorName').value.trim();
    const idType = document.getElementById('editVisitorIdType').value;
    const idNumber = document.getElementById('editVisitorIdNumber').value.trim();
    const phone = document.getElementById('editVisitorPhone').value.trim();
    
    if (!name || !idType || !idNumber) {
        alert('请填写必填字段');
        return;
    }
    
    try {
        const response = await apiRequest('admin/visitor_management.php', {
            method: 'PUT',
            body: JSON.stringify({
                action: 'update',
                id: parseInt(visitorId),
                name: name,
                id_type: idType,
                id_number: idNumber,
                phone: phone
            })
        });
        
        if (response.code === 200) {
            showAlert('visitorsAlert', '观众信息更新成功！', 'success');
            closeModal('editVisitorModal');
            loadVisitorList(); // 重新加载列表
        } else {
            alert(response.message || '更新失败');
        }
    } catch (error) {
        console.error('更新观众信息失败:', error);
        alert('更新观众信息失败：' + error.message);
    }
}

// 查看观众详情
async function viewVisitorDetail(visitorId) {
    try {
        const response = await apiRequest(`admin/visitor_management.php?action=detail&id=${visitorId}`);
        if (response.code === 200) {
            const visitor = response.data;
            showVisitorDetailModal(visitor);
        } else {
            alert(response.message || '获取详情失败');
        }
    } catch (error) {
        console.error('获取观众详情失败:', error);
        alert('获取观众详情失败：' + error.message);
    }
}

// 显示观众详情模态框
function showVisitorDetailModal(visitor) {
    document.getElementById('visitorDetailName').textContent = visitor.name || '-';
    document.getElementById('visitorDetailIdType').textContent = visitor.id_type || '-';
    document.getElementById('visitorDetailIdNumber').textContent = visitor.id_number || '-';
    document.getElementById('visitorDetailPhone').textContent = visitor.phone || '-';
    document.getElementById('visitorDetailUser').textContent = visitor.user_nickname || visitor.user_real_name || '-';
    document.getElementById('visitorDetailCreateTime').textContent = visitor.created_at || '-';
    
    // 显示模态框
    document.getElementById('visitorDetailModal').style.display = 'block';
}

// 删除观众
async function deleteVisitor(visitorId) {
    if (!confirm('确定要删除这个观众信息吗？此操作不可恢复！')) {
        return;
    }
    
    try {
        const response = await apiRequest('admin/visitor_management.php', {
            method: 'DELETE',
            body: JSON.stringify({
                action: 'delete',
                id: visitorId
            })
        });
        
        if (response.code === 200) {
            showAlert('visitorsAlert', '观众信息删除成功！', 'success');
            loadVisitorList(); // 重新加载列表
        } else {
            alert(response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除观众失败:', error);
        alert('删除观众失败：' + error.message);
    }
}

// 导出观众数据
async function exportVisitors() {
    try {
        const response = await apiRequest('admin/visitor_management.php?action=export');
        if (response.code === 200) {
            // 创建下载链接
            const blob = new Blob([JSON.stringify(response.data, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `常用观众数据_${new Date().toLocaleDateString('zh-CN')}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            showAlert('visitorsAlert', '数据导出成功！', 'success');
        } else {
            alert(response.message || '导出失败');
        }
    } catch (error) {
        console.error('导出数据失败:', error);
        alert('导出数据失败：' + error.message);
    }
}

// 批量删除观众
async function batchDeleteVisitors() {
    const checkedBoxes = document.querySelectorAll('.visitor-checkbox:checked');
    if (checkedBoxes.length === 0) {
        alert('请选择要删除的观众');
        return;
    }
    
    if (!confirm(`确定要删除选中的 ${checkedBoxes.length} 个观众信息吗？此操作不可恢复！`)) {
        return;
    }
    
    const visitorIds = Array.from(checkedBoxes).map(cb => parseInt(cb.value));
    
    try {
        const response = await apiRequest('admin/visitor_management.php', {
            method: 'DELETE',
            body: JSON.stringify({
                action: 'batch_delete',
                ids: visitorIds
            })
        });
        
        if (response.code === 200) {
            showAlert('visitorsAlert', '批量删除成功！', 'success');
            loadVisitorList(); // 重新加载列表
        } else {
            alert(response.message || '批量删除失败');
        }
    } catch (error) {
        console.error('批量删除失败:', error);
        alert('批量删除失败：' + error.message);
    }
}

// 全选/取消全选观众
function toggleSelectAllVisitors() {
    const selectAll = document.getElementById('selectAllVisitors');
    const checkboxes = document.querySelectorAll('.visitor-checkbox');
    
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAll.checked;
    });
}

// 核销员管理功能
async function toggleVerifierStatus(userId, currentStatus) {
    const isVerifier = currentStatus === 1;
    const action = isVerifier ? '取消核销员' : '设为核销员';
    
    if (!confirm(`确定要${action}吗？`)) {
        return;
    }
    
    try {
        const response = await apiRequest('admin_management.php?action=set_verifier', {
            method: 'POST',
            body: JSON.stringify({
                user_id: userId,
                is_verifier: isVerifier ? 0 : 1
            })
        });
        
        if (response.code === 200) {
            showAlert('usersAlert', `${action}成功！`, 'success');
            loadUsers(); // 重新加载用户列表
        } else {
            alert(response.message || `${action}失败`);
        }
    } catch (error) {
        console.error(`${action}失败:`, error);
        alert(`${action}失败：` + error.message);
    }
}

// 核销记录管理功能
async function loadVerificationLogs() {
    if (!hasPermission('verification.view')) {
        showAlert('verificationLogsAlert', '权限不足');
        return;
    }
    
    try {
        const response = await apiRequest('verification_center.php?action=admin_logs');
        if (response.code === 200) {
            const logs = response.data.logs;
            const stats = response.data.stats;
            
            // 更新统计数据
            document.getElementById('verificationTotalCount').textContent = stats.total || 0;
            document.getElementById('verificationTodayCount').textContent = stats.today || 0;
            document.getElementById('verificationPersonalCount').textContent = stats.personal || 0;
            document.getElementById('verificationTeamCount').textContent = stats.team || 0;
            
            const tbody = document.getElementById('verificationLogsTable');
            
            if (!logs || logs.length === 0) {
                tbody.innerHTML = '<tr><td colspan="9" class="loading">暂无核销记录</td></tr>';
                return;
            }
            
            tbody.innerHTML = logs.map(log => {
                const verifiedTime = new Date(log.verified_at).toLocaleString('zh-CN');
                const typeText = log.reservation_type === 'team' ? '团队' : '个人';
                
                return `
                    <tr>
                        <td>${log.id}</td>
                        <td>${log.reservation_id}</td>
                        <td><span class="badge" style="background: ${log.reservation_type === 'team' ? '#28a745' : '#007bff'}; color: white;">${typeText}</span></td>
                        <td>${log.visitor_name}</td>
                        <td>${log.visitor_phone}</td>
                        <td><code>${log.verification_code}</code></td>
                        <td>${log.verifier_name}</td>
                        <td>${verifiedTime}</td>
                        <td>${log.ip_address || '-'}</td>
                    </tr>
                `;
            }).join('');
            
        }
    } catch (error) {
        console.error('加载核销记录失败:', error);
        document.getElementById('verificationLogsTable').innerHTML = '<tr><td colspan="9" class="loading">加载失败</td></tr>';
        showAlert('verificationLogsAlert', '加载核销记录失败：' + error.message);
    }
}

// 搜索核销记录
async function searchVerificationLogs() {
    const dateStart = document.getElementById('verificationDateStart').value;
    const dateEnd = document.getElementById('verificationDateEnd').value;
    const typeFilter = document.getElementById('verificationTypeFilter').value;
    const searchTerm = document.getElementById('verificationSearch').value.trim();
    
    try {
        document.getElementById('verificationLogsTable').innerHTML = '<tr><td colspan="9" class="loading">搜索中...</td></tr>';
        
        const params = new URLSearchParams();
        params.append('action', 'admin_logs');
        if (dateStart) params.append('date_start', dateStart);
        if (dateEnd) params.append('date_end', dateEnd);
        if (typeFilter) params.append('type', typeFilter);
        if (searchTerm) params.append('search', searchTerm);
        
        const response = await apiRequest(`verification_center.php?${params.toString()}`);
        if (response.code === 200) {
            const logs = response.data.logs;
            const tbody = document.getElementById('verificationLogsTable');
            
            if (!logs || logs.length === 0) {
                tbody.innerHTML = '<tr><td colspan="9" class="loading">未找到匹配的记录</td></tr>';
                return;
            }
            
            tbody.innerHTML = logs.map(log => {
                const verifiedTime = new Date(log.verified_at).toLocaleString('zh-CN');
                const typeText = log.reservation_type === 'team' ? '团队' : '个人';
                
                return `
                    <tr>
                        <td>${log.id}</td>
                        <td>${log.reservation_id}</td>
                        <td><span class="badge" style="background: ${log.reservation_type === 'team' ? '#28a745' : '#007bff'}; color: white;">${typeText}</span></td>
                        <td>${log.visitor_name}</td>
                        <td>${log.visitor_phone}</td>
                        <td><code>${log.verification_code}</code></td>
                        <td>${log.verifier_name}</td>
                        <td>${verifiedTime}</td>
                        <td>${log.ip_address || '-'}</td>
                    </tr>
                `;
            }).join('');
        }
    } catch (error) {
        console.error('搜索核销记录失败:', error);
        document.getElementById('verificationLogsTable').innerHTML = '<tr><td colspan="9" class="loading">搜索失败</td></tr>';
        showAlert('verificationLogsAlert', '搜索核销记录失败：' + error.message);
    }
}

// 导出核销记录
async function exportVerificationLogs() {
    try {
        const dateStart = document.getElementById('verificationDateStart').value;
        const dateEnd = document.getElementById('verificationDateEnd').value;
        const typeFilter = document.getElementById('verificationTypeFilter').value;
        
        const params = new URLSearchParams();
        params.append('action', 'export_logs');
        if (dateStart) params.append('date_start', dateStart);
        if (dateEnd) params.append('date_end', dateEnd);
        if (typeFilter) params.append('type', typeFilter);
        
        // 创建下载链接
        const url = `../api/verification_center.php?${params.toString()}`;
        const link = document.createElement('a');
        link.href = url;
        link.download = `核销记录_${new Date().toISOString().split('T')[0]}.csv`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
    } catch (error) {
        console.error('导出数据失败:', error);
        alert('导出数据失败：' + error.message);
    }
}

// 页面切换时自动加载数据
document.addEventListener('DOMContentLoaded', function() {
    // 监听页面切换事件
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                const target = mutation.target;
                if (target.classList.contains('active') && target.id === 'verification-logs') {
                    loadVerificationLogs();
                }
            }
        });
    });
    
    // 观察所有页面内容元素
    document.querySelectorAll('.tab-content').forEach(function(element) {
        observer.observe(element, { attributes: true });
    });
});


// 存储选择的图片文件
let selectedChapterImages = [];
// 处理图片选择
document.addEventListener('DOMContentLoaded', function() {
    const imageInput = document.getElementById('addChapterImageInput');
    if (imageInput) {
        imageInput.addEventListener('change', handleChapterImageSelect);
    }
});

// 处理图片选择
function handleChapterImageSelect(event) {
    const files = Array.from(event.target.files);
    const maxSize = 5 * 1024 * 1024; // 5MB
    
    // 过滤无效文件
    const validFiles = files.filter(file => {
        if (!file.type.startsWith('image/')) {
            alert(`文件 ${file.name} 不是图片格式`);
            return false;
        }
        // if (file.size > maxSize) {
        //     alert(`文件 ${file.name} 超过5MB限制`);
        //     return false;
        // }
        return true;
    });
    
    // 添加到选择的图片数组
    selectedChapterImages.push(...validFiles);
    
    // 更新预览
    updateChapterImagePreview();
    
    // 清空input，允许重复选择相同文件
    event.target.value = '';
}

// 更新图片预览
function updateChapterImagePreview() {
    const previewContainer = document.getElementById('addChapterImagePreview');
    if (!previewContainer) return;
    
    previewContainer.innerHTML = '';
    
    selectedChapterImages.forEach((file, index) => {
        const previewItem = document.createElement('div');
        previewItem.className = 'image-preview-item';
        previewItem.innerHTML = `
            <img src="${URL.createObjectURL(file)}" alt="预览图">
            <div class="image-preview-remove" onclick="removeChapterImage(${index})">×</div>
        `;
        previewContainer.appendChild(previewItem);
    });
}

// 移除选择的图片
function removeChapterImage(index) {
    selectedChapterImages.splice(index, 1);
    updateChapterImagePreview();
}

// 清空选择的图片
function clearChapterImages() {
    selectedChapterImages = [];
    updateChapterImagePreview();
}
